Python Glossary Русский

Python 3.9+Byte sequencesfunction

bytearray.removeprefix

bytearray — stripping

Remove a given prefix if present (3.9+).

Syntax

ba.removeprefix(...)

You get a fresh bytearray back and the original stays as it was, so calling it for its side effect does nothing — assign the result. Exactly one copy of the prefix is removed, repeats stay put, and a missing prefix simply returns the data unchanged instead of raising.

Examples

print(bytearray(b'foobar').removeprefix(b'foo'))   # → bytearray(b'bar')
print(bytearray(b'foobar').removeprefix(b'bar'))   # → bytearray(b'foobar')
print(bytearray(b'foofoobar').removeprefix(b'foo'))   # → bytearray(b'foobar')
ba = bytearray(b'log:42'); print(ba.removeprefix(b'log:'), ba)   # → bytearray(b'42') bytearray(b'log:42')
print(bytearray(b'abc').removeprefix('a'))   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy