Python String translate() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String translate() method

The string translate() method in Python returns a string where each character is mapped to its corresponding character in the translation table.

The translation table is created by using the maketrans() method.

Syntax of translate() method
string.translate(table)

table: a translation table containing the 
       mapping between characters.
Example 1

Code

str1 = "Pylenin"

table = str1.maketrans("n", "m")

print(str1.translate(table))

Output

Pylemim

As you can see, all instances of n were replaced with m.

Example 2 - Mapping table with a dictionary

Code

mapping_dict = {"n":"m"}
str1 = "Pylenin"

table = str1.maketrans(mapping_dict)

print(str1.translate(table))

Output

Pylemim
Example 3 - Removing characters

Code

str1 = "Pylenin?"

table = str1.maketrans("","","?")

print(str1.translate(table))

Output

Pylenin

Since the 3rd argument is used to pass in the characters to be removed, the first 2 arguments are being left empty above.

We can achieve the same result by passing in a dictionary.

Code

mapping_dict= {"?":None}
str1 = "Pylenin?"

table = str1.maketrans(mapping_dict)

print(str1.translate(table))

Output

Pylenin

Just use None as values for characters you want removed from your string.

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide