Python Glossary Русский

all Python 3Byte sequencesfunction

bytearray.translate

bytearray — replace and translate

Map bytes through a 256-byte translation table.

Syntax

ba.translate(...)

The table must be exactly 256 bytes long (bytes.maketrans() builds one), otherwise you get a ValueError; None means "map nothing" and only applies delete. Deletion happens before mapping, and the whole operation is byte-by-byte, so it cannot rewrite multi-byte UTF-8 characters — but for plain byte swaps one pass beats a chain of replace calls.

Examples

print(bytearray(b'abc').translate(bytes.maketrans(b'a', b'X')))   # → bytearray(b'Xbc')
table = bytes.maketrans(b'abc', b'xyz')
print(bytearray(b'cabbage').translate(table))   # → bytearray(b'zxyyxge')
print(bytearray(b'a-b-c').translate(None, delete=b'-'))   # → bytearray(b'abc')
print(bytearray(b'1-800-555').translate(bytes.maketrans(b'0', b'O'), delete=b'-'))   # → bytearray(b'18OO555')
print(bytearray(b'abc').translate(None))   # → bytearray(b'abc')

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy