Bytearray Methods

bytearray.replace()

Replace non-overlapping occurrences from left to right. The replacement is not rescanned. An empty old pattern matches byte boundaries, including both ends. A zero count leaves the bytes unchanged, and a negative count removes the limit. In Python 3.13 the binary count argument remains positional-only, unlike str.replace. Always returns a new bytearray, even when unchanged.

Formal Syntax & Structure

python syntaxpython
data.replace(old, new, count=-1, /)

Parameters & Attributes

NameTypeDescription
oldbytes-likeLiteral binary subsequence to match.
newbytes-likeReplacement data, possibly empty.
countintMaximum replacements; negative means unlimited.

Return Value

bytearray

bytearray with requested literal replacements applied.

Working Example

Example Snippetpython
print(bytearray(b'a-a-a').replace(b'a', b'X', 2))print(bytearray(b'AB:CD').replace(b':', b''))print(bytearray(b'AB').replace(b'', b'-'))
Python Reference