bytes.replace()
Bytes are immutable, so this always allocates. When you are patching a large buffer repeatedly, that is the cost to watch — bytearray exists for exactly that case.
Demo
Every occurrence is replaced unless you pass a count. A sequence that is not present gives the original back unchanged — no error. Replacing with an empty value deletes. The empty-old case is the surprising one: an empty sequence matches at every gap, so the replacement is inserted before each byte and after the last. The multi-byte case works because both arguments were encoded the same way, which is exactly why replacing bytes across mismatched encodings goes wrong.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| old | bytes | yes | Sequence to look for. An empty value inserts new at every gap. |
| new | bytes | yes | Replacement. May be a different length, or empty to delete. |
| count | int | no (-1) | Maximum replacements. Negative or omitted means replace every occurrence. |
Return value
bytes — A NEW bytes object with occurrences of old replaced by new. The original is never modified.
Common patterns
unix = data.replace(b'\r\n', b'\n')
clean = data.replace(b'\x00', b'')
patched = data.replace(old, new, 1)
Examples
Pitfalls
data.replace(b'a', b'X') data
data = data.replace(b'a', b'X')
for old, new in rules: data = data.replace(old, new)
buf = bytearray(data) # edit slices in place
b'abc'.replace(b'', b'-')
if old: data = data.replace(old, new)
b'abc'.replace('a', b'X')
b'abc'.replace(b'a', b'X')
When to use
- Normalising line endings in binary-mode data
- Stripping or swapping a marker in a payload
- Small, one-off patches to a buffer
- Many edits to a large buffer → bytearray, edited in place
- The data is text → decode first and use str.replace
- Pattern matching rather than a literal → the re module works on bytes too
Notes
FAQ
Because bytes are immutable — replace builds a new object and returns it. If you did not assign the result, the original is still exactly as it was.
data = data.replace(b'a', b'X')