Python String translate()

Python String.translate() method translates the calling string based on the dictionary or mapping table given as argument. The translation is basically replacing specified characters with their respective replacements, and/or deleting specific characters.

In this tutorial, we will learn the syntax and examples for translate() method of String class.

Syntax

The syntax of String translate() method in Python is

str.translate(table)

where

ParameterRequired/OptionalDescription
tableRequiredDictionary or Mapping table. If a dictionary, then it specifies the replacements. If a mapping table, then it specifies the replacements and/or removals .
ADVERTISEMENT

Examples

Translate String using a Dictionary

In the following program, we take a string 'apple' in x, and replace 'p' with 't', and 'e' with 'm' using translate() method.

If we pass a dictionary to translate() method, then the search values and replacements must be provided as ASCII values.

Example.py

x = "apple"
result = x.translate({112: 116, 101: 109}) //{'p':'t', 'e': 'm'}
print("Original String    :", x)
print("Translated String  :", result)
Try Online

Output

Original String    : apple
Translated String  : attlm

Replace Characters based on Mapping

In the following program, we take a string 'apple' in x, create a mapping to replace 'p' with 't', 'e' with 'm', and delete the characters 'abc' using maketrans() method, and pass the mapping to translate() method.

Example.py

x = "apple"
mapping = x.maketrans('pe', 'tm', 'abc')
result = x.translate(mapping)
print("Original String    :", x)
print("Translated String  :", result)
Try Online

Output

Original String    : apple
Translated String  : ttlm

Conclusion

In this Python Tutorial, we learned how to translate a string, using String method – translate(), with examples.