bytes.translate()
One pass, many substitutions. Where chained replace calls each copy the whole buffer, translate rewrites every byte exactly once.
Demo
maketrans pairs up the two arguments byte by byte — the first byte of frm maps to the first byte of to, and so on — and translate then rewrites the data through that table. Bytes not mentioned pass through untouched, as the partial case shows. The mapping is strictly one byte to one byte, so the two arguments must be the same length; the last case shows the ValueError you get otherwise.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| table | bytes | None | yes | A 256-byte table, normally from bytes.maketrans. Pass None to only delete. |
| delete | bytes | no (b'') | Bytes to remove entirely. Applied as well as the table mapping. |
Return value
bytes — A new bytes object with every byte mapped through the table. Bytes listed in delete are removed entirely.
Common patterns
table = bytes.maketrans(b'abc', b'xyz') out = data.translate(table)
clean = data.translate(None, b'\r\x00')
rot = bytes.maketrans(plain_alphabet, shifted_alphabet)
Examples
Pitfalls
data.translate(bytes.maketrans(b'\r\n', b'\n'))
data.replace(b'\r\n', b'\n')
b'abc'.translate(b'short')
b'abc'.translate(bytes.maketrans(b'a', b'x'))
'héllo'.encode().translate(bytes.maketrans(b'\xc3', b'\x41'))
'héllo'.translate(str.maketrans('é', 'e'))
data.translate(table) data
data = data.translate(table)
When to use
- Swapping several single bytes in one pass
- Stripping a set of unwanted byte values
- Fixed substitution ciphers and byte-level normalisation
- Hot paths where chained replace calls cost too much
- Multi-byte sequences → replace
- UTF-8 encoded text → decode and use str.translate
- Pattern-based edits → the re module, which works on bytes
Notes
FAQ
Each replace copies the entire buffer, so five substitutions mean five full passes. translate does them all in one pass through a lookup table — the win grows with both the buffer size and the number of mappings.
data.translate(bytes.maketrans(b"abc", b"xyz"))