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.
Python code
22 linesdef 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
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
- Use `bytes.maketrans` for translating byte strings instead of Unicode.
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.