python - 为什么 str.translate 在 Python 3 中不起作用?

标签 python python-3.x

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

最佳答案

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

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

关于python - 为什么 str.translate 在 Python 3 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17020661/

相关文章:

python - pyplot 图例条目中的空格?

python - PyDev 已安装但未显示在 ADT 中

python - 创建开放的街道 map View

python - 在 Python 中使用循环解析 XML

Python:循环遍历变量列表

python - Django - 如何基于具有 OneToOneField 的用户模型查询用户个人资料

python - 使用 Cython 包装具有 OpenCV 参数的 C++ 函数

python - 通过电子邮件发送 PDF

python-3.x - ruamel yaml 为转储禁用别名

python - 单词搜索的递归函数