translate()
method takes the translation table to replace/translate characters in the given string as per the mapping table.
The translation table is created by the static method maketrans().
The syntax of the translate()
method is:
string.translate(table)
String translate() Parameters
translate()
method takes a single parameter:
- table - a translation table containing the mapping between two characters; usually created by
maketrans()
Return value from String translate()
translate()
method returns a string where each character is mapped to its corresponding character as per the translation table.
Example 1: Translation/Mapping using a translation table with translate()
# first string
firstString = "abc"
secondString = "ghi"
thirdString = "ab"
string = "abcdef"
print("Original string:", string)
translation = string.maketrans(firstString, secondString, thirdString)
# translate string
print("Translated string:", string.translate(translation))
Output
Original string: abcdef Translated string: idef
Here, the translation mapping translation contains the mapping from a, b and c
to g, h and i
respectively.
But, the removal string thirdString resets the mapping to a
and b
to None
.
So, when the string is translated using translate()
, a
and b
are removed, and c
is replaced i
outputting idef
.
Note: If you cannot understand what's going inside maketrans(), please refer to String maketrans().
Example 2: Translation/Mapping with translate() with manual translation table
# translation table - a dictionary
translation = {97: None, 98: None, 99: 105}
string = "abcdef"
print("Original string:", string)
# translate string
print("Translated string:", string.translate(translation))
Output
Original string: abcdef Translated string: idef
Here, we don't create a translation table from maketrans()
but, we manually create the mapping dictionarytranslation.
This translation is then used to translate string
to get the same output as the previous example.
Also Read: