Let\'s say I have the string \'2okjser823ab\'. How can I remove all the numbers from the string using .translate()?
I see that in Python 2.x you can do something li
You may use the strip
function :
strings="tycoon0123456789999"
strings.strip("0123456789")
It looks like it's a bit harder in Python 3; not sure why.
Here's what you can do:
>>> import string
>>> translation = str.maketrans(string.ascii_letters, string.ascii_letters, string.digits)
>>> "2okjser823ab".translate(translation)
'okjserab'
You may need to expand string.ascii_letters
with whatever else you expect as input (string.ascii_letters + string.punctuation + string.whitespace
, for example).
Edit: I can't find it clearly in the documentation for str.maketrans
, but if you use an empty string for the first two arguments, everything will be mapped 1 to 1, but the deletion part (the third argument) still happens:
>>> translation = str.maketrans("", "", string.digits)
>>> "2eeŷýéeokjser823 ab.;\t".translate(translation)
'eeŷýéeokjser ab.;\t'