Home >>Python String Methods >Python String translate() Method

Python String translate() Method

Python String translate() Method

Python string translate() method is used to return a string where all the characters are mapped to its corresponding character in the translation table.

Syntax:
string.translate(table)

Parameter Values

Parameter Description
table This parameter defines a translation table containing the mapping between two characters.
Here is an example of Python translate() method:

str1 = "xr"
str2 = "PT"
str3 = "a"
trg = "xHxraxOINr"
table = trg.maketrans(str1, str2, str3) 
print ("The string before translating is : ", end ="") 
print (trg) 
print ("The string after translating is : ", end ="") 
print (trg.translate(table))

Output:
The string before translating is : xHxraxOINr
The string after translating is : PHPTPOINT
Example 2:

str1 = "rcd"
str2 = "inh"
trg = "Abdrmacyu"
table = trg.maketrans(str1, str2) 
print ("The string before translating is : ", end ="") 
print (trg) 
print ("The string after translating is : ", end ="") 
print (trg.translate(table))

Output:
The string before translating is : Abdrmacyu
The string after translating is : Abhimanyu