Python 3 translation function

I am using Python 3 and I want to translate my file names so as not to have numbers. The translation function does not work in Python 3. How can I translate file names so that they do not have numbers?

This is a block of code that does not work:

file_name = "123hello.jpg" file_name.translate(None, "0123456789") 

thanks

+15
function python translate
source share
4 answers

str.translate still exists, the interface has changed a bit:

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

I am using ver3.6.1 and the translation does not work. What is the strip () method:

 file_name = 123hello.jpg file_name.strip('123') 
+5
source share

.translate accepts a translation table:

Return a copy of the string S in which each character was matched through this translation table. The table should implement search / indexing via getitem , for example, a dictionary or list, matching Unicode orders with Unicode numbers, strings or None. If this operation raises a LookupError, the character remains untouched. Characters matched by None are deleted.

So you can do something like:

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

Delete only numbers on the left

 new_name = str.lstrip('1234567890') 

Delete only numbers on the right

 new_name = str.rstrip('123456780') 

Delete number left and right

 new_name = str.strip('1234567890') 

Delete all numbers

 new_name = str.translate(str.maketrans('', '', '1234567890')) 
+3
source share

All Articles