Подтвердить что ты не робот

Почему str.translate не работает в Python 3?

Почему 'a'.translate({'a':'b'}) возвращает 'a' вместо 'b'? Я использую Python 3.

4b9b3361

Ответ 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.