Python 3 中的翻译函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41708770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:28:00  来源:igfitidea点击:

Translate function in Python 3

pythonfunctiontranslate

提问by Dean Clancy

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?

我正在使用 Python 3,我想将我的文件名转换为没有数字。translate 函数在 Python 3 中似乎不起作用。如何将文件名转换为没有数字?

This is the block of code that doesn't work:

这是不起作用的代码块:

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

Thanks

谢谢

回答by wim

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

str.translate还在,只是界面变了一点:

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

回答by juanpa.arrivillaga

.translatetakes a translation table:

.translate需要一个翻译表:

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.

返回字符串 S 的副本,其中每个字符都已通过给定的转换表映射。该表必须通过getitem实现查找/索引,例如字典或列表,将 Unicode 序数映射到 Unicode 序数、字符串或无。如果此操作引发 LookupError,则字符保持不变。映射到 None 的字符被删除。

So you can do something like:

因此,您可以执行以下操作:

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

回答by Mativo

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

我正在使用 ver3.6.1 并且翻译不起作用。起作用的是strip() 方法,如下所示:

file_name = 123hello.jpg

file_name.strip('123')

回答by udit sharma

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'))