Sub topic 12
Mapping and Deleting Characters with translate
This chapter assumes you know how str.replace works and that strings are immutable, so every method returns a new string. You should also be comfortable reading dictionaries, tuples, and function definitions. By the end you will be able to build translation tables, use them to substitute and delete characters in one pass, and recognize the cases where translate is the wrong tool.
Why translate exists
replace swaps one substring for another. When you need many single-character substitutions, chaining replace calls gets clumsy, and it can give wrong answers. Swapping two letters shows the problem:
text = "abba"
chained = text.replace("a", "b").replace("b", "a")
print(chained) # aaaa
table = str.maketrans("ab", "ba")
print(text.translate(table)) # baabThe chained version first turns every a into b. The second call then turns all the b characters, old and new, into a. translate reads each character of the original string once and looks it up in a table. It never re-reads its own output, so the swap works.
The translation table
A translation table is a mapping from Unicode code points (integers) to replacements. str.maketrans builds one for you. It is a static method, so you call it on the class, not on a string instance. You can inspect the result:
table = str.maketrans("ab", "xy")
print(table) # {97: 120, 98: 121}The keys 97 and 98 are ord("a") and ord("b"). The values 120 and 121 are ord("x") and ord("y").
When translate meets a character, it looks up that character's code point in the table and acts on the value:
| Value found for the character | Result |
|---|---|
| A string (any length, including empty) | The character is replaced by that string |
| An integer | The character is replaced by the character with that code point |
| `None` | The character is deleted |
| No entry at all | The character is kept unchanged |
Three ways to call maketrans
str.maketrans accepts one argument or two or three. The table below summarizes the forms.
| Call | Meaning |
|---|---|
| `str.maketrans(x, y)` | Two strings of equal length. `x[i]` becomes `y[i]`. |
| `str.maketrans(x, y, z)` | Same as above, and every character in `z` is deleted. |
| `str.maketrans(mapping)` | A dict. Keys are single characters or integer code points. Values are strings, integers, or `None`. |
Substituting with two strings
table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table)) # xxyyzzThe two strings must have the same length. If they do not, maketrans raises ValueError immediately, which is better than a silent misalignment.
try:
str.maketrans("abc", "xy")
except ValueError as err:
print(err) # the first two maketrans arguments must have equal lengthDeleting with the third argument
The third argument lists characters to remove. Pass empty strings for the first two when you only want deletion:
delete_vowels = str.maketrans("", "", "aeiou")
print("education".translate(delete_vowels)) # dctnIf a character appears in both the mapping and the deletion string, deletion wins:
table = str.maketrans("abc", "xyz", "b")
print("abcabc".translate(table)) # xzxzUsing a dict for longer replacements
The two-string form can only map one character to one character. A dict removes that limit, because values can be strings of any length:
table = str.maketrans({"é": "e", "ß": "ss", "\t": " "})
print("Café\tStraße".translate(table)) # Cafe StrasseHere ß becomes the two characters ss. The dict form also handles deletion with None:
table = str.maketrans({"-": None, " ": None})
print("555 123-4567".translate(table)) # 5551234567maketrans converts single-character string keys to integers for you. If you pass a dict straight to translate without maketrans, the keys must already be integers, such as ord("-"). A dict with string keys passed directly to translate matches nothing, and the string comes back unchanged.
raw = {"-": None}
print("a-b".translate(raw)) # a-b (no match: key is a str)
print("a-b".translate({ord("-"): None})) # abBecause of this, build tables with maketrans unless you have a reason not to.
A worked example: normalizing typographic quotes
Text copied from word processors often contains curly quotes that break comparisons and parsers. A table fixes them in one pass:
QUOTES = str.maketrans({
"\u2018": "'", # left single quote
"\u2019": "'", # right single quote
"\u201c": '"', # left double quote
"\u201d": '"', # right double quote
"\u200b": None, # zero-width space
})
sample = "\u201cIt\u2019s\u201d\u200b"
print(sample.translate(QUOTES)) # "It's"Build the table once at module level, as QUOTES is here. Rebuilding it on every call wastes time, and a named constant documents what the cleanup does.
Removing punctuation
The string module provides ready-made character sets. Combining string.punctuation with the three-argument form gives a short punctuation remover:
import string
STRIP_PUNCT = str.maketrans("", "", string.punctuation)
print("Hello, World! It's 5 o'clock.".translate(STRIP_PUNCT))
# Hello World Its 5 oclockThis removes only ASCII punctuation. Characters such as ¿ or — are not in string.punctuation, so they stay. If your data is international, add them to the deletion string or the dict.
You can feed this into a cleanup pipeline from the chaining chapter:
def normalize(text):
return " ".join(text.translate(STRIP_PUNCT).split()).casefold()
print(normalize(" Hello, World! It's me. ")) # hello world its meGotchas and limits
Keys must be single characters
translate works character by character. A multi-character key cannot match anything, and maketrans rejects it:
try:
str.maketrans({"ab": "x"})
except ValueError as err:
print(err) # string keys in translate table must be of length 1To replace a substring such as "ab", use replace. To replace a pattern, use re.sub.
It works on code points, not on what you see
An accented letter can be stored as one code point (é, U+00E9) or as two (e followed by the combining accent U+0301). A table keyed on the one-code-point form does not match the two-code-point form:
table = str.maketrans({"\u00e9": "e"})
print("caf\u00e9".translate(table)) # cafe
print(len("cafe\u0301".translate(table))) # 5, unchangedIf your input may use either form, normalize it first with unicodedata.normalize before translating.
It always returns a new string
As with every str method, translate does not modify the original. Assign the result:
s = "a-b"
s.translate(str.maketrans("-", "_"))
print(s) # a-b
s = s.translate(str.maketrans("-", "_"))
print(s) # a_bThe table does not have to be a dict
translate only requires an object that supports lookup with table[code_point] and raises LookupError (such as KeyError or IndexError) when the code point is absent. A dict is the usual choice. A custom class with __getitem__ also works, which is useful for rules like "delete every control character" that would need thousands of dict entries.
class DropControl:
def __getitem__(self, code_point):
if code_point < 32:
return None
raise LookupError(code_point)
print("a\x00b\x07c".translate(DropControl())) # abcChoosing between replace, translate, and re
| Task | Best tool |
|---|---|
| Replace one known substring, optionally limiting the count | `replace` |
| Replace or delete many single characters in one pass | `translate` |
| Swap characters without them interfering | `translate` |
| Replace by pattern, position, or context | `re.sub` |
If you find yourself listing characters that "look like" something, such as all digits or all whitespace, check whether a pattern like \d or \s in re says it more clearly.
Exercise
Write a single translate call that turns "ab-12-cd" into "ab cd". Hyphens must become spaces and digits must be removed. Use string.digits for the digits.
Show answer
Use the three-argument form so that substitution and deletion happen together: import string table = str.maketrans("-", " ", string.digits) print("ab-12-cd".translate(table)) # ab cd The hyphen maps to a space and every digit is deleted. The two hyphens each become a space, so two spaces remain where the digits were removed.
Exercise
A teammate writes "a--b".translate(str.maketrans({"--": "-"})) to collapse double hyphens. What happens, and what should they use instead?
Show answer
str.maketrans raises ValueError: string keys in translate table must be of length 1, because translate only maps single characters. For a fixed substring they should use "a--b".replace("--", "-"). If runs of hyphens can be any length, re.sub(r"-+", "-", text) handles that.
Exercise
Why does "abba".replace("a", "b").replace("b", "a") return "aaaa", while "abba".translate(str.maketrans("ab", "ba")) returns "baab"?
Show answer
The chained replace calls run one after another on the result of the previous call. After the first call every character is b, so the second call turns them all into a. translate looks up each character of the original string once and never re-reads its own output, so each a becomes b and each b becomes a independently.