Python String Translate: Using str.translate()
Replace or remove characters with Python's str.translate() and str.maketrans(), and learn when translate() is a better fit than replace().

When you need to replace or remove characters from a Python string, str.translate() offers a fast and flexible approach. Unlike replace(), which substitutes exact substrings, translate() uses a translation table: each character is looked up, and the table returns a replacement, None for deletion, or leaves the character unchanged. That makes it useful for bulk character transformations, especially when you need to handle many characters at once.
Understanding str.translate() and Translation Tables
The str.translate() method takes a translation table and returns a new string where each character has been mapped according to that table. The table is usually built with str.maketrans(), but you can also pass a custom mapping directly to translate(). The method processes the entire string in one pass, which makes it efficient for large inputs.
# Basic usage
table = str.maketrans({'a': '1', 'b': '2'})
result = "abc".translate(table)
print(result) # '12c'str.translate() accepts a table object that maps a Unicode ordinal (an integer code point) to another ordinal, a replacement string, or None. When a value is None, the character is removed from the output. This is a key difference from replace(), which cannot delete characters without replacing them with an empty string.
Building a Translation Table with str.maketrans()
str.maketrans() has three forms. The first takes a dictionary, as shown above. The second takes two strings of equal length and maps each character in the first to the corresponding character in the second. The third takes three strings: the first two map characters, and the third lists characters to delete.
# Two-string form: map 'a' to '1', 'b' to '2'
table = str.maketrans('ab', '12')
print("abc".translate(table)) # '12c'
# Three-string form: also delete 'x' and 'y'
table = str.maketrans('ab', '12', 'xy')
print("axbyc".translate(table)) # '12c'The two-string and three-string forms are concise for one-to-one mappings. The dictionary form is useful when you want to specify a few mappings or use None to delete a character. str.maketrans() is designed for one-character replacements and deletions; if you need to replace one character with a longer string, build a custom table and pass it directly to translate().
Practical Example: Removing and Replacing Characters
A common task is stripping punctuation from text. With translate(), you can build a table that maps each punctuation character to None and apply it in one line.
import string
remove_punct = str.maketrans('', '', string.punctuation)
text = "Hello, world! How's it going?"
clean = text.translate(remove_punct)
print(clean) # 'Hello world Hows it going'You can also replace characters with another single character. For instance, converting newlines to spaces:
table = str.maketrans({'\n': ' ', '\r': ' '})
multiline = "line1\nline2\rline3"
print(multiline.translate(table)) # 'line1 line2 line3'This approach is more readable than chaining multiple replace() calls and avoids the risk of accidentally replacing substrings you didn't intend to touch.
translate() vs replace(): Choosing the Right Tool
replace() is the right choice when you need to replace a specific substring, especially if it appears multiple times and you want to control the count. translate() is better when you need to handle a set of individual characters, because it processes the whole string in a single pass and can delete characters directly.
| Operation | replace() | translate() |
|---|---|---|
| Replace exact substring | Yes | No: maps individual characters |
| Delete characters | No (must replace with '') | Yes (map to None) |
| Multiple replacements in one pass | No (chained calls) | Yes |
| Unicode-aware | Yes | Yes |
| Performance with many character mappings | Repeated passes, especially when chained | Single pass over the string |
For example, to replace all vowels with a dash, translate() is cleaner:
table = str.maketrans('aeiou', '-----')
print("hello".translate(table)) # 'h-----'If you tried the same with replace(), you'd need five separate calls, each scanning the string.
Handling Unicode and Non-ASCII Characters
translate() operates on Unicode code points, so it handles non-ASCII characters without issue. You can map accented characters, emojis, or any Unicode symbol. Characters not present in the table are left unchanged.
# Map accented characters to their ASCII equivalents
table = str.maketrans({'é': 'e', 'ü': 'u', 'ñ': 'n'})
print("café".translate(table)) # 'cafe'The dictionary form accepts integer ordinals as well as single-character string keys, which can be useful when you build a table programmatically.
Performance Considerations for Large Text
Because translate() scans the string once and uses a lookup table, it can be faster than a chain of replace() calls when you need to handle many characters. For a small mapping, table construction is usually minor compared with scanning a large string.
import time
# Simulate a large string
large_text = "a" * 1_000_000 + "b" * 1_000_000
# Using translate
table = str.maketrans({'a': 'x', 'b': 'y'})
start = time.perf_counter()
translated = large_text.translate(table)
print("translate:", time.perf_counter() - start)
# Using replace (two calls)
start = time.perf_counter()
replaced = large_text.replace('a', 'x').replace('b', 'y')
print("replace:", time.perf_counter() - start)The exact speed difference depends on your Python implementation, input size, and replacement pattern, so measure on representative data if performance is critical. The main structural advantage of translate() is that it avoids multiple passes and temporary strings.
Common Pitfalls and Edge Cases
One common mistake is forgetting that translate() returns a new string; the original remains unchanged. Also, if you use the two-string form of maketrans(), the strings must have equal length, otherwise a ValueError is raised.
# This raises ValueError: the first two maketrans arguments must have equal length
try:
str.maketrans('abc', '12')
except ValueError as e:
print(e)To delete a character, map it to None. The convenience forms of str.maketrans() accept one-character replacement strings, so do not use an empty string as a replacement value.
When building a translation table for deletion only, you can pass an empty string for the first two arguments and the deletion list as the third:
table = str.maketrans('', '', '.,;')
print("a.b,c;".translate(table)) # 'abc'Finally, str.translate() is the string version; the bytes type also has translate(), but its API is different. bytes.translate() expects a bytes-like table of length 256 and handles deletion through a separate argument.
Combining translate() with Other String Operations
You can use translate() as a preprocessing step before other operations like splitting or regex matching. For example, to normalize whitespace before tokenizing:
normalize_ws = str.maketrans({'\t': ' ', '\n': ' ', '\r': ' '})
text = "line1\tline2\nline3"
normalized = text.translate(normalize_ws)
tokens = normalized.split()
print(tokens) # ['line1', 'line2', 'line3']Because translate() works on the entire string, it's a good fit for data cleaning pipelines where you need consistent character transformations before further processing. It keeps the logic declarative and avoids the complexity of nested replace() calls.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.