为什么str.translate不能在Python 3中运行?

时间:2013-06-10 09:27:02

标签: python python-3.x

为什么'a'.translate({'a':'b'})会返回'a'而不是'b'?我正在使用Python 3。

1 个答案:

答案 0 :(得分:57)

使用的键是字符的序数,而不是字符本身:

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