Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate function in Python 3 [duplicate]

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

like image 676
Dean Clancy Avatar asked Jan 17 '17 23:01

Dean Clancy


People also ask

How do I translate in Python 3?

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.

What does translate () do in Python?

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.

How do I use Maketrans in Python 3?

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.

How do you translate text in Python?

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.


3 Answers

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

>>> table = str.maketrans(dict.fromkeys('0123456789'))
>>> '123hello.jpg'.translate(table)
'hello.jpg'
like image 50
wim Avatar answered Oct 13 '22 14:10

wim


.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'
>>>
like image 8
juanpa.arrivillaga Avatar answered Oct 13 '22 14:10

juanpa.arrivillaga


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')
like image 4
Mativo Avatar answered Oct 13 '22 14:10

Mativo