Bytes Methods

bytes.translate()

Return an immutable bytes result by deleting occurrences of original byte values listed in delete and replacing remaining byte values using a 256-byte lookup table. Use None as the table to perform deletion only. Deletion is based on the original input, not the substituted output; each retained byte undergoes one lookup and the output is never recursively translated. The delete argument is a collection of individual byte values, not a substring. A table must contain 256 bytes; CPython 3.13.5 also accepts contiguous bytes-like tables such as bytearray or memoryview. This is not a Unicode character mapping; applying it directly to multibyte encodings can corrupt text. Do not depend on object identity for unchanged immutable results.

Formal Syntax & Structure

python syntaxpython
data.translate(table, /, delete=b'')

Parameters & Attributes

NameTypeDescription
tablebytes | None256-byte translation table or None for deletion only. Contiguous bytes-like tables also work on the tested runtime.
deletebytes-likeIndividual byte values to omit; empty by default.

Return Value

bytes

Translated binary sequence, with original input unchanged.

Working Example

Example Snippetpython
data = bytes(b"A-B!B")table = bytes.maketrans(b"AB", b"xy")result = data.translate(table, delete=b"-!")print(result)print(data)print(data.translate(None, b"B"))
Python Reference