all Python 3Byte sequencesfunction
bytes.translate
bytes — replace and translate
Map bytes through a 256-byte translation table.
Syntax
b.translate(...)
The table has to be exactly 256 bytes long (bytes.maketrans builds it for you), or None when all you want is the delete argument. Translation happens byte by byte, so running it over UTF-8 text with non-ASCII characters mangles multi-byte sequences — decode first and use str.translate there. The payoff is that a single pass rewrites many byte values at once, where you would otherwise chain several replace calls.
Examples
print(b'abc'.translate(bytes.maketrans(b'a', b'X'))) # → b'Xbc'
print(b'hello'.translate(bytes.maketrans(b'el', b'ip'))) # → b'hippo'
print(b'a-b-c'.translate(None, b'-')) # → b'abc'
print(b'a1b2'.translate(bytes.maketrans(b'ab', b'AB'), b'12')) # → b'AB'
print(b'abc'.translate(None)) # → b'abc'
print(b'abc'.translate(b'xy')) # → ValueError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy