为什么 str.translate 在 Python 3 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17020661/
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-19 00:15:07 来源:igfitidea点击:
Why doesn't str.translate work in Python 3?
提问by fhucho
Why does 'a'.translate({'a':'b'})return 'a'instead of 'b'? I'm using Python 3.
为什么'a'.translate({'a':'b'})返回'a'而不是'b'?我正在使用 Python 3。
回答by jamylak
The keys used are the ordinals of the characters, not the characters themselves:
使用的键是字符的序数,而不是字符本身:
'a'.translate({ord('a'): 'b'})
It's easier to use str.maketrans
使用起来更方便 str.maketrans
>>> 'a'.translate(str.maketrans('a', 'b'))
'b'
>>> help(str.translate)
Help on method_descriptor:
translate(...)
S.translate(table) -> str
Return a copy of the string S, where all characters have been mapped
through the given translation table, which must be a mapping of
Unicode ordinals to Unicode ordinals, strings, or None.
Unmapped characters are left untouched. Characters mapped to None
are deleted.

