Bytes Methods

bytes.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. Returns bytes.

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

bytes

bytes with requested literal replacements applied.

Working Example

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