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
| Name | Type | Description |
|---|---|---|
| old | bytes-like | Literal binary subsequence to match. |
| new | bytes-like | Replacement data, possibly empty. |
| count | int | Maximum 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'-'))