Python String maketrans() Method

By Lenin Mishra

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

Python String maketrans() method

The maketrans() method in Python is used to specify the list of characters that need to be replaced or deleted in the whole string.

It returns a translation table that can be used with the translate() method.

Syntax of maketrans() method
string.maketrans(str1, str2, str3)

str1 : Specifies the list of characters that need to be replaced.
str2 : Specifies the list of characters with which the characters need to be replaced.
str3 : Specifies the list of characters that need to be deleted.
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 - Using a dictionary with maketrans()

Code

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

table = str1.maketrans(mapping_dict)

print(str1.translate(table))

Output

Pylemim
Example 3 - How to remove characters with maketrans()

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