[英]Why doesn't str.translate work in Python 3?
Why does 'a'.translate({'a':'b'})
return 'a'
instead of 'b'
?为什么
'a'.translate({'a':'b'})
返回'a'
而不是'b'
? I'm using Python 3.我正在使用 Python 3。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.