There's got to be an easy way to do this (fwd)

Alex Martelli aleaxit at yahoo.com
Thu Jul 5 16:40:40 EDT 2001


"Lulu of the Lotus-Eaters" <mertz at gnosis.cx> wrote in message
news:mailman.994355168.2401.python-list at python.org...
    ...
>   filter(lambda c:c.isdigit(), '(123)/456-7890')
>
> Thirteen characters shorter than Emile's, and still no [re] :-).
>
> Personally, I even find it easier to read.  YMMV.

filter(string.isdigit, '(123)/456-7890')

is six fewer characters and IMHO more readable still.


A few more characters (because you need some preparation,
once, outside of the inner loop), but blazingly fast in the
inner loop:

nondigits = ''.join([chr(x) for x in range(0,256) if not chr(x).isdigit()])
identity = string.maketrans('','')

and then in the inner loop

'(123)/456-7890'.translate(identity, nondigits)


Alex






More information about the Python-list mailing list