How to Translate Characters in a String with str.maketrans in Python

Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.

Easy Python 3.9+ Aug 9, 2026 Strings & text 11 views 0 copies

Python code

22 lines
Python 3.9+
def translate_demo():
    # Build a translation table: a→1, e→2, i→3, o→4, u→5
    table = str.maketrans("aeiou", "12345")
    
    text = "Hello, Python world! Keep coding, friend."
    translated = text.translate(table)
    
    print(f"Original: {text}")
    print(f"Translated: {translated}")
    
    # Example with deletions (remove spaces and exclamation marks)
    delete_table = str.maketrans("", "", " !")
    compressed = text.translate(delete_table)
    print(f"Compressed: {compressed}")
    
    # Example with mapping to None (removes character)
    custom_table = str.maketrans({"o": None, "l": "L"})
    modified = text.translate(custom_table)
    print(f"Modified: {modified}")

if __name__ == "__main__":
    translate_demo()

Output

stdout
Original: Hello, Python world! Keep coding, friend.
Translated: H2ll4, Pyth4n w4rld! K22p c4d3ng, fr32nd.
Compressed: Hello,Pythonworld!Keepcoding,friend.
Modified: HeLLo, Python worLd! Keep coding, friend.

How it works

The str.maketrans method builds a translation table when given two equal-length strings (each character maps to the corresponding character). If you pass three arguments, the third string's characters are deleted from the output. You can also use a dictionary mapping single characters to replacement characters or None (to delete). The str.translate method applies that table to the whole string, making it much faster than a loop for heavy character substitution. It's ideal for tasks like replacing vowels, normalizing text, or removing punctuation.

Common mistakes

  • Passing two strings of unequal length to `str.maketrans` raises a ValueError.
  • Forgetting that the third argument to `maketrans` deletes characters, not replaces them.
  • Using `str.replace` repeatedly when a single `translate` call is more efficient.
  • Trying to map to multi-character strings; `translate` only supports single-character or `None` replacements.

Variations

  1. Use `bytes.maketrans` for translating byte strings instead of Unicode.
  2. Call `str.translate` with a dictionary directly if you only need a few replacements.

Real-world use cases

  • Sanitizing user input by replacing accented characters with ASCII equivalents before storing in a database.
  • Removing all whitespace and punctuation from a string for clean text analysis or tokenization.
  • Translating a string to a fictional language (e.g., Leet speak) for a game feature or data obfuscation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.