0
0
PythonHow-ToBeginner · 3 min read

How to Use maketrans and translate in Python

In Python, use str.maketrans() to create a translation table that maps characters to their replacements, and then apply it with str.translate() to transform the string. This combination lets you replace, delete, or map characters efficiently in one step.
📐

Syntax

str.maketrans() creates a translation table for character replacements. It can take three arguments: x and y are strings of equal length where each character in x is replaced by the character at the same position in y. The optional third argument is a string of characters to delete.

str.translate() applies this translation table to a string, returning a new string with replacements and deletions done.

python
table = str.maketrans(x, y, z)
new_string = original_string.translate(table)
💻

Example

This example replaces vowels with numbers and removes punctuation from the string.

python
text = "Hello, World!"
# Replace vowels: a->1, e->2, i->3, o->4, u->5
# Remove punctuation: , and !
translation_table = str.maketrans("aeiou", "12345", ",!")
result = text.translate(translation_table)
print(result)
Output
H2ll4 W4rld
⚠️

Common Pitfalls

  • Passing strings of different lengths to maketrans() for x and y causes a ValueError.
  • For deleting characters, only provide them in the third argument; do not include them in x or y.
  • Remember translate() returns a new string; it does not change the original string.
python
try:
    # Wrong: different lengths for x and y
    table = str.maketrans("abc", "de")
except ValueError as e:
    print(f"Error: {e}")

# Correct usage
table = str.maketrans("abc", "def")
print("abcabc".translate(table))
Output
Error: the first two maketrans arguments must have equal length defdef
📊

Quick Reference

str.maketrans(x, y, z)

  • x: string of characters to replace
  • y: string of replacement characters (same length as x)
  • z: string of characters to delete

str.translate(table) applies the translation table to a string.

FunctionPurpose
str.maketrans(x, y, z)Create translation table for replacements and deletions
str.translate(table)Apply translation table to string

Key Takeaways

Use str.maketrans() to create a mapping table for character replacements and deletions.
Apply the translation table with str.translate() to get the transformed string.
Ensure the first two arguments to maketrans() are strings of equal length.
Characters to delete go only in the third argument of maketrans().
translate() returns a new string; it does not modify the original.