Python Glossary Русский

Python 3.1+Byte sequencesfunction

bytes.maketrans

bytes — replace and translate

A static method building a translation table for translate().

Syntax

b.maketrans(...)

Both arguments must have the same length or you get a ValueError; the result is a table of exactly 256 bytes in which every byte you did not mention maps to itself. Translation happens byte by byte, not character by character, so applying such a table to UTF-8 text will wreck multi-byte characters — for text use str.maketrans, which builds a mapping of code points. The table cannot delete anything: translate takes a separate delete argument for that.

Examples

print(len(bytes.maketrans(b'ab', b'AB')))   # → 256
print(b'hello'.translate(bytes.maketrans(b'el', b'ip')))  # → b'hippo'
print(b'AATTGC'.translate(bytes.maketrans(b'ATGC', b'TACG')))  # → b'TTAACG'
print(bytes.maketrans(b'a', b'A')[97])  # → 65
print(bytes.maketrans(b'ab', b'A'))  # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy