all Python 3Byte sequencesfunction
bytearray.replace
bytearray — replace and translate
Return a copy with occurrences replaced.
Syntax
ba.replace(...)
bytearray is mutable, yet replace never edits in place — it hands back a fresh copy, so the result is lost unless you assign it. Both arguments must be bytes-like; a str, or a bare int for a single byte, raises TypeError.
Examples
print(bytearray(b'aaa').replace(b'a', b'b')) # → bytearray(b'bbb')
print(bytearray(b'aaa').replace(b'a', b'b', 2)) # → bytearray(b'bba')
print(bytearray(b'a-b-c').replace(b'-', b'')) # → bytearray(b'abc')
print(bytearray(b'abc').replace(b'z', b'y')) # → bytearray(b'abc')
ba = bytearray(b'aaa'); ba.replace(b'a', b'b'); print(ba) # → bytearray(b'aaa')
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy