Translate function in Python 3 [duplicate] Translate function in Python 3 [duplicate] python python

Translate function in Python 3 [duplicate]


str.translate is still there, the interface has just changed a little:

>>> table = str.maketrans(dict.fromkeys('0123456789'))>>> '123hello.jpg'.translate(table)'hello.jpg'


.translate takes a translation table:

Return a copy of the string S in which each character has been mapped through the given translation table. The table must implement lookup/indexing via getitem, for instance a dictionary or list, mapping Unicode ordinals to Unicode ordinals, strings, or None. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

So you can do something like:

>>> file_name = "123hello.jpg">>> file_name.translate({ord(c):'' for c in "1234567890"})'hello.jpg'>>>


I'm using ver3.6.1 and translate did not work. What did work is the strip() method as follows:

file_name = 123hello.jpgfile_name.strip('123')