问题
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
回答1:
str.translate is still there, the interface has just changed a little:
>>> table = str.maketrans(dict.fromkeys('0123456789'))
>>> '123hello.jpg'.translate(table)
'hello.jpg'
回答2:
.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'
>>>
回答3:
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')
回答4:
Only remove numbers from left
new_name = str.lstrip('1234567890')
Only remove numbers from right
new_name = str.rstrip('123456780')
Remove number from left and right
new_name = str.strip('1234567890')
Remove all numbers
new_name = str.translate(str.maketrans('', '', '1234567890'))
来源:https://stackoverflow.com/questions/41708770/translate-function-in-python-3