There's got to be an easy way to do this

Remco Gerlich scarblac at
Fri Jul 6 08:14:38 CEST 2001

Lindstrom Greg - glinds <Greg.Lindstrom at> wrote in comp.lang.python:
> I am reading in a phone number field and would like to throw away everything
> except the digits.  Being an old C programmer, I know how I would do this.
> Even with my limited knowledge of Python, I know how I would do it:
> 	stripped_phone=''
> 	for c in phone_number:
> 		if c in digits: 
> 			stripped_phone += c
> but with all of the data structure support native to Python, I'm sure there
> is "an obvious way" to do it (perhaps it's because I'm not Dutch:-).

Some other solutions:
# Closest to yours, readable
stripped_phone = ''
for c in phone_number:
   if c.isdigit():
      stripped_phone += c

# The same with filter, too bad we need a lambda
stripped_phone = filter(lambda c: c.isdigit(), phone_number)

# Translate might be fast, but not very readable (only the last line needs to
# be inside a tight loop)
import string
transtable = string.maketrans("","")
nodigit = filter(lambda c: not c.isdigit(), transtable)
stripped_phone = phone_number.translate(transtable, nodigit)

The last one might be fastest inside a tight loop, or maybe the re solution
someone else gave.

However, if your code isn't a speed problem, just leave it.

Funny, I think there's one obvious way to do this in Perl :-)
($x =~ s/[^0-9]//g)

Remco Gerlich

More information about the Python-list mailing list