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

Lulu of the Lotus-Eaters mertz at gnosis.cx
Thu Jul 5 17:49:31 EDT 2001


"Alex Martelli" <aleaxit at yahoo.com> wrote:
>   filter(lambda c:c.isdigit(), '(123)/456-7890')
> Thirteen characters shorter than Emile's, and still no [re] :-).

|filter(string.isdigit, '(123)/456-7890')
|is six fewer characters and IMHO more readable still.

  >>> filter(string.isdigit, '(123)/456-7890')
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  NameError: There is no variable named 'string'

Or did you expect me to "spend" 13 characters on 'import string'? :-)

Btw. Alex is quite right on his speedy solution:

  def AM_trans(iters):
      nondigits = ''.join([chr(x) for x in range(0,256) if not chr(x).isdigit()])
      identity = string.maketrans('','')
      for i in iters:
          '(123)/456-7890'.translate(identity, nondigits)

-   500-       str_join2   flt_lmbda3  traditional   AM_trans
         5 :    0.07         0.05         0.08         0.02
        10 :    0.15         0.11         0.16         0.06
        50 :    0.72         0.57         0.79         0.24

Yours, Lulu...




More information about the Python-list mailing list