tags:

views:

57

answers:

4

In Python 2.6, I can run the following fine to strip out chars like -()

'(123) 456-7890'.translate(None, '-(), ')

Python2.5 translate does not accept None, how can I do the above in 2.5?

+3  A: 

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.

AndiDog
Good answer, more to the spirit of the question!
Mark
A: 

Regular Expressions.

>>> import re
>>> re.sub('\-|\(|\)| ','','(123) 456-7890')
1234567890
Mark
+3  A: 

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'
gimel
+1  A: 

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.

ΤΖΩΤΖΙΟΥ