bytes.maketrans(from, to) returns a bytes object of length 256 that translate() can use. Position b in the table holds the byte that b should become.
Every byte in from maps to the byte at the same position in to; all other positions map to themselves. Both arguments must be bytes-like and of equal length.
bytes.maketrans() is a static method: call it on the class itself, as bytes.maketrans(...), not on a particular bytes object. bytearray.maketrans() exists too and builds the same kind of table.
Syntax
Call it on the bytes class with two equal-length bytes objects.
python
table = bytes.maketrans(from_bytes, to_bytes)
result = data.translate(table)
Call
What it does
bytes.maketrans(b"ab", b"AB")
A 256-byte table mapping a to A and b to B.
bytes.maketrans(b"", b"")
The identity table, equal to bytes(range(256)).
bytes.maketrans(b"ab", b"x")
Raises ValueError: lengths differ.
If a byte appears twice in from, the later mapping wins.
Method signatures
python
static bytes.maketrans(from, to)
# from, to: bytes-like objects of the same length
# returns a bytes object of length 256
Parameters
Parameter
Description
from
The bytes to be replaced.
to
The replacement bytes, position by position. Must be the same length as from.
Return Value
Return Value
Description
bytes
A 256-byte translation table.
Python Examples
Example 1 — Inspect a Translation Table
Build a small table, look at two of its 256 entries, and apply it.
Many to one. Two different source bytes may map to the same target byte.
Single pass. Translation handles both separators at once instead of two replace() calls.
Ready to split. With one separator left, split() returns the three fields.
Example 3 — The Identity Table and the Length Rule
An empty mapping gives the identity table, mismatched lengths fail, and bytearray.maketrans() builds a table too.
python
identity = bytes.maketrans(b"", b"")
print(identity == bytes(range(256)))
try:
bytes.maketrans(b"ab", b"x")
except ValueError:
print("from and to must have the same length")
print(bytearray.maketrans(b"0", b"O")[48])
Output
True
from and to must have the same length
79
How It Works
Identity table. With nothing to map, entry b is simply b, the same as bytes(range(256)).
Lengths must match. Two source bytes and one target byte cannot be paired, so ValueError is raised.
bytearray version. Entry 48 (the digit zero) now holds 79, the code for the letter O.
Frequently Asked Questions
A bytes object of length 256 that maps each byte value to its replacement, for use with translate().
It is a static method: it does not need an existing object. bytes.maketrans(a, b) is the normal way to call it.
ValueError is raised.
You cannot. Build the mapping with maketrans() and pass the bytes to delete as the second argument of translate().
Yes. Any 256-byte bytes-like table works with both bytes.translate() and bytearray.translate().