Python bytes.replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
bytes method

Definition

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)
CallWhat 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

ParameterDescription
oldThe byte sequence to replace (bytes-like).
newThe replacement bytes (bytes-like); may be empty to delete old.
countOptional. Maximum number of replacements, counted from the left. Default -1, which replaces every occurrence.

Return Value

Return ValueDescription
bytesA 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"))

How It Works

  1. Two bytes to one. Each two-byte \r\n becomes a single \n, so the result is two bytes shorter.
  2. Only the first. With count=1 the second line ending keeps its \r.
  3. 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.

python
log = b"user=ada token=abc123 status=ok"

print(log.replace(b"abc123", b"******"))
print(log.replace(b"=", b": "))
print(log.replace(b"missing", b"x") == log)

How It Works

  1. Same length. Six asterisks replace the six-byte token, keeping the line layout.
  2. Longer replacement. Each one-byte = becomes the two bytes :, so the line grows.
  3. No match, no change. When old is absent, the result compares equal to the original.

Example 3 — Escape Special Bytes in a Binary Frame

Some serial protocols reserve 0x7E as a frame flag and 0x7D as an escape byte. Escape them inside the payload, then undo it.

python
payload = b"\x01\x7e\x02\x7d\x03"

stuffed = payload.replace(b"\x7d", b"\x7d\x5d").replace(b"\x7e", b"\x7d\x5e")
print(stuffed.hex(" "))
restored = stuffed.replace(b"\x7d\x5e", b"\x7e").replace(b"\x7d\x5d", b"\x7d")
print(restored == payload)

How It Works

  1. Escape byte first. Replacing 0x7D before 0x7E prevents the newly inserted escape bytes from being escaped again.
  2. Readable result. hex() with a space separator (Python 3.8+) shows each payload byte as two hex digits.
  3. Reverse order to decode. Undoing the escapes restores the exact original payload.

Frequently Asked Questions

Pass a count: data.replace(old, new, 1).
Yes. Use an empty replacement: data.replace(b"\r", b""). For deleting many different single bytes, translate(None, delete) is faster.
The arguments are str. Use b"a" and b"b".
No. It returns a new bytes object.
For one-to-one byte mappings, build a table with bytes.maketrans() and call translate(). For longer sequences, chain replace() calls in a safe order.

Next: bytes.rfind()

Return the highest index of a byte sequence, or -1 if it is not found.

rfind() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful