bytes.replace() returns a new bytes object in which every non-overlapping occurrence of old is replaced by new. Pass count to replace only the first count occurrences, scanning from the left.
old and new can have different lengths, so the result can grow or shrink. Common jobs include converting Windows line endings, hiding secrets in log data, and escaping special bytes in binary protocols.
bytes.replace() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.replace(...). No import is needed, and bytearray objects have the same method.
Syntax
Give the bytes to find and the bytes to put in their place.
python
result = data.replace(old, new)
result = data.replace(old, new, count)
Call
What it does
b"a-b-c".replace(b"-", b"+")
Returns b'a+b+c'.
b"aaa".replace(b"a", b"b", 2)
Returns b'bba'.
b"abc".replace(b"", b"-")
Returns b'-a-b-c-': an empty old matches between all bytes.
If old is not found, the result equals the original.
Method signatures
python
bytes.replace(old, new[, count])
# old, new: bytes-like objects
# count: maximum number of replacements; omitted or -1 means all
Parameters
Parameter
Description
old
The byte sequence to replace (bytes-like).
new
The replacement bytes (bytes-like); may be empty to delete old.
count
Optional. Maximum number of replacements, counted from the left. Default -1, which replaces every occurrence.
Return Value
Return Value
Description
bytes
A copy with the replacements made.
Python Examples
Example 1 — Convert CRLF Line Endings to LF
Data from a Windows file or a network protocol often uses \r\n. Replace all of them, or just the first one with count.
python
data = b"one\r\ntwo\r\nthree"
print(data.replace(b"\r\n", b"\n"))
print(data.replace(b"\r\n", b"\n", 1))
print(data.count(b"\r\n"))
Output
b'one\ntwo\nthree'
b'one\ntwo\r\nthree'
2
How It Works
Two bytes to one. Each two-byte \r\n becomes a single \n, so the result is two bytes shorter.
Only the first. With count=1 the second line ending keeps its \r.
Source unchanged.count() on the original still finds both CRLF pairs.
Example 2 — Redact a Secret in a Log Line
Hide a token before writing a log line, change separators, and see what happens when the text to replace does not exist.