为什么 str.translate 在 Python 3 中不起作用? [英] Why doesn't str.translate work in Python 3?
本文介绍了为什么 str.translate 在 Python 3 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 'a'.translate({'a':'b'})
返回 'a'
而不是 'b'
>?我使用的是 Python 3.
Why does 'a'.translate({'a':'b'})
return 'a'
instead of 'b'
? I'm using Python 3.
推荐答案
使用的键是字符的序数,而不是字符本身:
The keys used are the ordinals of the characters, not the characters themselves:
'a'.translate({ord('a'): 'b'})
使用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.
这篇关于为什么 str.translate 在 Python 3 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文