bytes.removeprefix(prefix) checks whether the data starts with prefix. If it does, it returns a copy with that prefix cut off once; otherwise it returns the data unchanged.
It replaces the common two-step pattern of startswith() followed by slicing, and it avoids the set behavior of lstrip(), which removes individual bytes rather than an exact sequence.
bytes.removeprefix() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.removeprefix(...). No import is needed, and bytearray objects have the same method. New in Python 3.9.
Syntax
Pass the exact byte sequence to remove from the start (Python 3.9+).
python
result = data.removeprefix(prefix)
Call
What it does
b"HTTP/1.1".removeprefix(b"HTTP/")
Returns b'1.1'.
b"abc".removeprefix(b"x")
Returns b'abc': no match, no change.
b"aab".removeprefix(b"a")
Returns b'ab': removed only once.
The match is exact and case-sensitive.
Method signatures
python
bytes.removeprefix(prefix, /)
# new in Python 3.9; prefix: bytes-like object
Parameters
Parameter
Description
prefix
The exact bytes to remove from the start. Must be bytes-like.
Return Value
Return Value
Description
bytes
data[len(prefix):] when the data starts with prefix, otherwise a copy of the data.
Python Examples
Example 1 — Remove a Protocol Prefix from a Status Line
Strip HTTP/ to get the version number, and see that a wrong or wrongly-cased prefix changes nothing.
python
status = b"HTTP/1.1 200 OK"
print(status.removeprefix(b"HTTP/"))
print(status.removeprefix(b"FTP/"))
print(status.removeprefix(b"http/"))