32

Why does 'a'.translate({'a':'b'}) return 'a' instead of 'b'? I'm using Python 3.

Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
fhucho
  • 33,107
  • 40
  • 127
  • 181

1 Answers1

60

The keys used are the ordinals of the characters, not the characters themselves:

'a'.translate({ord('a'): 'b'})

It's easier to use 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.
martineau
  • 112,593
  • 23
  • 157
  • 280
jamylak
  • 120,885
  • 29
  • 225
  • 225