Python Glossary Русский

Python 3.9+Byte sequencesfunction

bytes.removeprefix

bytes — stripping

Remove a given prefix if present (3.9+).

Syntax

b.removeprefix(...)

Unlike lstrip() this matches the whole sequence and removes exactly one occurrence: b'foofoobar' becomes b'foobar', not b'bar'. A missing prefix is not an error — the value comes back unchanged, so guarding with startswith() first is pointless. The argument must be bytes-like; passing a str raises TypeError.

Examples

print(b'foobar'.removeprefix(b'foo'))   # → b'bar'
print(b'foobar'.removeprefix(b'baz'))  # → b'foobar'
print(b'GET /index'.removeprefix(b'GET '))  # → b'/index'
print(b'foofoobar'.removeprefix(b'foo'))  # → b'foobar'
print(b'xxfoo'.lstrip(b'xf'))  # → b'oo'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy