str.maketrans()
Build the translation table used by str.translate. Three shapes: dict form, two-string form, and two-string-plus-delete form.
Demo
The demo shows the RESULTING TABLE as a dict from ordinal to replacement. Real code feeds it into str.translate. The two-string form (from + to) requires equal lengths — a mismatch raises ValueError. The optional third argument "del" is a set of characters to DELETE (mapped to None). Passing empty strings for from + to with a non-empty del is a valid "delete only" call.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| x | dict | str | yes | Dict form: {ord(char) → replacement} directly. Two-string form: characters to be mapped (must equal length of y). Three-string form: same as two-string plus a `z` string of characters to DELETE. |
| y | str | no (None) | The replacement characters — must match the length of x. Only used when x is a string. |
| z | str | no (None) | Characters to DELETE — mapped to None in the resulting table. Only used with the two-string form of x/y. |
Return value
dict — A dict mapping Unicode ordinals (integers) to replacement values (integers, strings, or None). Feed the result to str.translate(). Three input shapes are supported — see parameters.
Common patterns
table = str.maketrans("abc", "xyz")
no_vowels = str.maketrans("", "", "aeiou")
table = str.maketrans({"&": "and", "@": " at "})
table = str.maketrans("abc", "xyz", "!?")
Examples
Pitfalls
str.maketrans("abc", "xy")
str.maketrans("abc", "xyz")
str.maketrans("a", "x")["a"]
str.maketrans("a", "x")[ord("a")]
str.maketrans("a", "xyz")
str.maketrans({"a": "xyz"})
"hi".maketrans("a", "x") # receiver ignored
str.maketrans("a", "x")
When to use
- Any time you would use str.translate — always build with maketrans
- Multi-character substitutions via the dict form
- Batch character deletion via the three-string form
- Building a reusable table once and applying to many strings
- One-off substring replacement → str.replace is more direct
- Regex-based transformations → re.sub
- Case transformations → lower / upper / casefold / swapcase
- Multi-char keys — dict form allows multi-char VALUES only, not keys
Notes
FAQ
maketrans BUILDS the table; translate APPLIES it. Two separate steps — you almost always chain them in one expression: `s.translate(str.maketrans(...))`.