Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't str.translate work in Python 3?

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

like image 403
fhucho Avatar asked Jun 10 '13 09:06

fhucho


People also ask

How do I translate in 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.

How do I use Maketrans in Python 3?

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.

Is there a translate function in Python?

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.


1 Answers

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. 
like image 159
jamylak Avatar answered Oct 12 '22 15:10

jamylak