What's the Python2.5 equivalent of Python2.6 translate with None as first param?
In Python 2.6, I can run the following fine to strip out chars like -()
'(123) 456-7开发者_StackOverflow中文版890'.translate(None, '-(), ')
Python2.5 translate does not accept None, how can I do the above in 2.5?
That should be possible with maketrans
:
import string
'(123) 456-7890'.translate(string.maketrans('', ''), '-(), ')
But you can also use regular expressions which is more readable.
Use string.maketrans
with empty arguments to create the identity translation table:
string.maketrans(from, to)
Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length.
>>> import string
>>> identity = string.maketrans("", "")
>>> '(123) 456-7890'.translate(identity, '-(), ')
'1234567890'
As an alternative, you can always keep only the digits:
def strip_nondigits(text):
return filter(type(text).isdigit, text)
>>> strip_nondigits('(123) 456-7890')
'1234567890'
This should be more robust against spurious characters. The type(text)
makes it work for unicode objects too.
Regular Expressions.
>>> import re
>>> re.sub('\-|\(|\)| ','','(123) 456-7890')
1234567890
精彩评论