Xodarap777 Xodarap777 - 4 months ago 8
Python Question

Reversing str.translate in Python

If I want to remove the numbers from "He123llo Wor456ld!" with translate, I can

from string import digits
str = "He123llo Wor456ld!"
str = str.translate(None, digits)
print str


>> Hello World!


How would I reverse this to get
123456
via translate?

Answer

You could use something like this

from string import digits
s = "He123llo Wor456ld!" 
s_ = s.translate(None, digits)
s = s.translate(None, s_)
print s

>>> 123456