【问题标题】:Why doesn't str.translate work in Python 3?为什么 str.translate 在 Python 3 中不起作用?
【发布时间】:2017-06-17 18:27:00
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 2021-03-23
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2021-04-12
    相关资源
    最近更新 更多