all Python 3Byte sequencesfunction
bytes.replace
bytes — replace and translate
Return a copy with occurrences of a subsequence replaced.
Syntax
b.replace(...)
Both arguments must be bytes-like; handing in a str raises TypeError rather than quietly working, which is the usual stumble right after opening a file in binary mode. Matching runs left to right with no overlaps, and nothing is modified in place — even on a bytearray the method hands back a fresh object.
Examples
print(b'aaa'.replace(b'a', b'b')) # → b'bbb'
print(b'aaa'.replace(b'a', b'b', 2)) # → b'bba'
print(b'2026-07-27'.replace(b'-', b'')) # → b'20260727'
print(b'abc'.replace(b'z', b'!')) # → b'abc'
print(b'ab'.replace(b'', b'-')) # → b'-a-b-'
print(b'abc'.replace('a', 'x')) # → TypeError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy