Why does 'a'.translate({'a':'b'})
return 'a'
instead of 'b'
? I'm using Python 3.
Python 3 String translate() Method The translate() method returns a copy of the string in which all characters have been translated using table (constructed with the maketrans() function in the string module), optionally deleting all characters found in the string deletechars.
Python 3 - String maketrans() MethodThe maketrans() method returns a translation table that maps each character in the intabstring into the character at the same position in the outtab string. Then this table is passed to the translate() function. Note − Both intab and outtab must have the same length.
The translate() method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table. Use the maketrans() method to create a mapping table. If a character is not specified in the dictionary/table, the character will not be replaced.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With