How to translate the content of a string in Python

First of all let’s see what translation means in Python. The translate() method returns a string that is translated (one or more characters were changed).

>>> s1 = 'Dan Dumitrache'
>>> s1_tr = s1.maketrans('D', 'M')
>>> s1.translate(s1_tr)
'Man Mumitrache'

The translation map (s1_tr) is applied to the entire string to accomplish more than one replacement. The string data type contains a helper function called maketrans() that creates a translation table that maps each character in the first parameter to the character at the same position in the second parameter.

You could replace more than a character:

>>> s1 = 'Dan Dumitrache'
>>> s1_tr = s1.maketrans('Dnu', 'Xyz')
>>> s1.translate(s1_tr)
'Xay Xzmitrache'

In this example ‘D’ is replaced by ‘X’, ‘n’ is replaced by ‘y’, and ‘u’ is replaced by ‘z’.
You could also delete characters from a string by setting the translation table to None.

>>> s1 = 'Dan Dumitrache'
>>> s1_tr = s1.maketrans({'D': None, 'a': None})
>>> s1.translate(s1_tr)
'n umitrche'

In this example the letters ‘D’ and ‘a’ are set to None so they wont be displayed.

Leave a Reply