stripping a string

Peter Otten __peter__ at web.de
Mon Sep 15 12:21:49 EDT 2003


Tim Williams wrote:

> Jeff Epler <jepler at unpythonic.net> wrote in message
> news:<mailman.1063499902.1786.python-list at python.org>...
>> If you want to remove all digits from the string, then use
>> str.translate, not regular expressions:
>>     import string
>>     identity_transformation = string.maketrans('', '')
>> 
>>     def remove_digits(s):
>> return s.translate(identity_transformation, string.digits)
>> 
>> >>> s = 'ANL LN32'
>> >>> remove_digits(s)
>> 'ANL LN'
>> 
>> If you want to remove digits from the end of the string, then use
>> str.strip(), not a regular expression:
>> >>> s.rstrip(string.digits)
>> 'ANL LN'
>> 
>> Jeff
> 
> 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'
>>> print re.sub('[0-9]', '', s)
AN LN

whereas

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

is *different*.

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

Peter





More information about the Python-list mailing list