Logo

Programming-Idioms

  • Ruby
  • Python

Idiom #221 Remove all non-digits characters

Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

import re
t = re.sub(r"\D", "", s)
from string import digits
t = ''.join(x for x in s if x in digits)
t = s.delete("^0-9")

^ Meaning: everything but.
(require '[clojure.string :as str])
(let [s "1a22b3c4de5f6"
      t (str/replace s #"[^\d]" "")]
  (println t))

Uses a regex to get only the digit characters.

New implementation...