Bytearray Methods

bytearray.translate()

Return a new mutable bytearray 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. The receiver is not mutated, including when the result is unchanged.

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

bytearray

Translated binary sequence, with original input unchanged.

Working Example

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