stripping a string

Andrew Bennetts andrew-pythonlist at puzzling.org
Mon Sep 15 21:54:02 EDT 2003


Peter Otten wrote:
> Tim Williams wrote:
> > 
> > I don't understand. What's wrong with
> > 
> >>>> import re
> >>>> s = 'ANL LN32'
> >>>> s=re.sub('[0-9]', '', s)
> >>>> print s
> > ANL LN
> 
> Nothing is *wrong*, but
> 
> >>> import re
> >>> s = 'AN21 LN32'

[...]

> >>> import string
> >>> print s.rstrip(string.digits)
> AN21 LN
> 
> is *different*.

In that case, you could do:

>>> import re
>>> s = 'AN21 LN32'
>>> print re.sub('[0-9]*$', '', s)
AN21 LN

> translate() gives the same result as re.sub(), but should be much faster
> (haven't timed it though).

I can never remember off the top of my head how to use maketrans or whatever
it's called so that I can use translate (it's not that it's hard, it's
simply that I can never remember it without looking it up).  Despite their
flaws, I find it easier to remember how to write regular expressions.

-Andrew.






More information about the Python-list mailing list