str.maketrans()

Build the translation table used by str.translate. Three shapes: dict form, two-string form, and two-string-plus-delete form.

String classmethodPython 2.6+Live demo
Common call
str.maketrans("abc", "xyz")
Returns
a dict — always with integer keys
Replaces
hand-building `{ord("a"): ord("x"), ord("b"): ord("y")}` dicts
Watch out
two-string form requires EQUAL lengths — mismatch raises ValueError
str.maketrans(x[, y[, z]])
dict

Demo

Live evaluation
Try:
Inputs
fromstrcharacters to replace
tostrreplacements, same length
delstrcharacters to delete (optional)
Output
'abc'.maketrans('xyz', None)
{'97': 120, '98': 121, '99': 122}

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

NameTypeRequiredDescription
xdict | stryesDict 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.
ystrno (None)The replacement characters — must match the length of x. Only used when x is a string.
zstrno (None)Characters to DELETE — mapped to None in the resulting table. Only used with the two-string form of x/y.

Return value

dictA 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

Straightforward character swap
Two strings of equal length — position-wise substitution.
table = str.maketrans("abc", "xyz")
Delete-only table
Empty from/to plus a delete string.
no_vowels = str.maketrans("", "", "aeiou")
Explicit dict form for multi-char replacements
The dict form allows string values (not just single characters).
table = str.maketrans({"&": "and", "@": " at "})
Swap AND delete in one call
All three arguments at once — substitute some chars, delete others.
table = str.maketrans("abc", "xyz", "!?")

Examples

1. Basic two-string
str.maketrans("abc", "xyz")
Returns
{97: 120, 98: 121, 99: 122} # ordinals!
2. Delete-only
str.maketrans("", "", "aeiou")
Returns
{97: None, 101: None, 105: None, ...}
3. Two-string + delete
str.maketrans("ab", "xy", "z")
Returns
{97: 120, 98: 121, 122: None}
4. Dict form
str.maketrans({"&": "and"})
Returns
{38: "and"}
5. Feed to translate
"a&b".translate(str.maketrans({"&": "and"}))
Returns
"aandb"

Pitfalls

1. Two-string lengths MUST match
A common source of ValueError. The two-string form is strict — a mismatch raises before any translation happens.
Length mismatch
str.maketrans("abc", "xy")
ValueError: the first two maketrans arguments must have equal length
Same length
str.maketrans("abc", "xyz")
valid table
2. Returns a dict of ORDINALS, not characters
The output looks weird when you inspect it — keys are integers, not characters. This is by design: str.translate wants ordinals. You almost never index into the result directly.
Ordinal keys
str.maketrans("a", "x")["a"]
KeyError: 'a' # not the key
Use ord()
str.maketrans("a", "x")[ord("a")]
120 # ord("x")
3. Dict form allows string values; two-string form does not
When x is a dict, values may be strings (multi-character replacements). When x and y are strings, values are single characters. For multi-character replacements, use the dict form.
Multi-char in two-string form
str.maketrans("a", "xyz")
ValueError: the first two maketrans arguments must have equal length
Dict form
str.maketrans({"a": "xyz"})
{97: "xyz"}
4. It is a CLASSMETHOD
Called on the str class, not on a string instance. Works on instances too but reads confusingly — the receiver is ignored.
Instance style
"hi".maketrans("a", "x")   # receiver ignored
valid but confusing
Class form
str.maketrans("a", "x")
clear intent

When to use

Use it
  • 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
Reach for something else
  • 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

Complexity
O(n) in the total size of the inputs — one pass to build the dict
Return
dict — always with integer keys (Unicode ordinals)
CPython impl
Objects/unicodeobject.c :: unicode_maketrans_impl
Memory
One dict allocated, sized to the input
Thread-safe
Yes — a pure computation

FAQ

maketrans BUILDS the table; translate APPLIES it. Two separate steps — you almost always chain them in one expression: `s.translate(str.maketrans(...))`.

History

2.6
string.maketrans available; used with str.translate.
3.0
Became str.maketrans as a classmethod; supports Unicode ordinals; adds the dict form.