I am using Python 3 and I want to translate my file names to have no numbers. The translate function doesn't seem to work in Python 3. How can I translate the file names to have no numbers?
This is the block of code that doesn't work:
file_name = "123hello.jpg"
file_name.translate(None, "0123456789")
Thanks
Python 3 String translate() Method The translate() method returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars.
The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced.
Python 3 - String maketrans() MethodThe maketrans() method returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note − Both intab and outtab must have the same length.
Translating Text Documents You can also translate text documents via Google Translate API. All you have to do is to read the text file in Python using the open method, read the text and pass it to the translate() method.
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.jpg
file_name.strip('123')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With