Tutorial Study Image

Python translate()

The translate() function in python helps to replace some characters from the string with the characters specified in the given mapping table or dictionary. The mapping table can be created using the maketrans() method.


string.translate(table) #where table may be a dictionary or mapping table
 

translate() Parameters:

The translate() function takes a single parameter. If we use a dictionary, we must use ASCII codes instead of characters.

Parameter Description Required / Optional
table a table containing the mapping between two characters Required

translate() Return Value

The return value will be a string. If we are not specified the character in the dictionary/table, the character will not be replaced.

Input Return Value
string mapped string

Examples of translate() method in Python

Example 1: How to translate a string using translate()?


# define string
String1 = "abc"
String2 = "ghi"
String3 = "ab"

string = "abcdef"
print("Before Translation:", string)

mapping= string.maketrans(String1, String2, String3)

# translate string
print("After Translation:", string.translate(mapping))
 

Output:


Before Translation:abcdef
After Translation:idef

Example 2: How to translate a string using translate() and manual translation table?


# translation table 
mapping = {97: None, 98: None, 99: 105}

string = "abcdef"
print("Before Translation:", string)

# translate string
print("After Translation:", string.translate(mapping))
 

Output:


Before Translation:abcdef
After Translation:idef