Python string maketrans() method with example

The maketrans() method is a built-in method in Python’s str class that creates a translation table. This translation table can be used with the translate() method to perform character-by-character translations or deletions in a string.

Syntax:

str.maketrans(x, y, z)

x: If only one argument is passed, it must be a dictionary. The dictionary specifies the mapping of Unicode ordinals (integers) or characters to their translations. If a character is not present as a key in the dictionary, it will not be replaced or deleted.

y: If two arguments are passed, it must be two strings with equal length. Each character in the first string is a replacement to its corresponding index in the second string.

z: If three arguments are passed, each character in the third argument will be mapped to None.

How to use the maketrans() method:

original_string = "Hello, World!"
translation_table = str.maketrans("o", "x")
translated_string = original_string.translate(translation_table)

print(translated_string) # Output: Hellx, Wxrld!

Example 1

Removing Punctuation from a String.

import string

def remove_punctuation(text):
  translation_table = str.maketrans("", "", string.punctuation)
  return text.translate(translation_table)

sentence = "Hello, World! How are you?"
cleaned_sentence = remove_punctuation(sentence)

print(cleaned_sentence)

Output:

Hello World How are you

Example 2

Unicode Character Translation.

translation_table = str.maketrans({8364: None})

text = "€Price: €19.99"
translated_text = text.translate(translation_table)

print(translated_text)

Output:

Price: 19.99