bytes.startswith() returns True if the bytes begin with prefix and False otherwise. Pass a tuple of prefixes to accept any of them in one call.
Its classic use is checking a magic number: the fixed bytes at the start of a file that identify its format, such as b"\x89PNG" or b"%PDF-". Optional start and end let you test a field in the middle of a packet.
bytes.startswith() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.startswith(...). No import is needed, and bytearray objects have the same method.
Syntax
Pass one prefix or a tuple of prefixes; start and end are optional.
python
ok = data.startswith(prefix)
ok = data.startswith((prefix1, prefix2))
ok = data.startswith(prefix, start, end)
Call
What it does
b"%PDF-1.7".startswith(b"%PDF")
Returns True.
b"GIF89a".startswith((b"GIF87a", b"GIF89a"))
Returns True: any tuple item may match.
b"\x00\x01AB".startswith(b"AB", 2)
Returns True: checking starts at index 2.
b"abc".startswith(b"")
Returns True: every object starts with empty bytes.
Unlike find(), startswith() does not accept an int; pass a one-byte bytes object such as b"\x00".
Method signatures
python
bytes.startswith(prefix[, start[, end]])
# prefix: bytes-like object or tuple of bytes-like objects
Parameters
Parameter
Description
prefix
A bytes-like object, or a tuple of them. A str or int raises TypeError.
start
Optional. Index where the comparison begins.
end
Optional. Index where the compared slice ends.
Return Value
Return Value
Description
True
The slice data[start:end] begins with prefix (or one of the tuple items).
False
It does not.
Python Examples
Example 1 — Detect a File Type from Its Magic Number
Read the first few bytes of a file and compare them with known signatures. A tuple handles formats that have more than one valid signature.
python
def kind(blob):
if blob.startswith(b"\x89PNG"):
return "png"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"%PDF-"):
return "pdf"
return "unknown"
print(kind(b"\x89PNG\r\n\x1a\n"))
print(kind(b"GIF89a\x10\x00"))
print(kind(b"%PDF-1.7"))
print(kind(b"PK\x03\x04"))
Output
png
gif
pdf
unknown
How It Works
Non-ASCII signature. PNG files start with the byte 0x89 followed by PNG; the escape \x89 writes that byte in the literal.
Two GIF versions. The tuple accepts both GIF87a and GIF89a in a single check.
Text signature. PDF files begin with the ASCII bytes %PDF- and a version number.
Fallback.PK\x03\x04 is the ZIP signature, which this function does not know, so it returns "unknown".
Example 2 — Check a Field at a Fixed Offset
Many binary packets start with a short header. Use start to check what comes after it without slicing first.
Header first. The packet begins with the two header bytes \x01\x00, so the payload is not at index 0.
Skip the header. With start=2 the comparison begins at the payload and succeeds.
End cuts the slice.packet[2:4] is only b'HE', too short to start with b"HEL", so the result is False.
Empty prefix. Every bytes object starts with b"".
Example 3 — Prefixes Must Be bytes, Not str or int
Check an HTTP request line correctly, then see the two argument types that startswith() rejects and a simple alternative for a single byte value.
python
line = b"GET /status HTTP/1.1"
print(line.startswith(b"GET"))
try:
line.startswith("GET")
except TypeError:
print("prefix must be bytes, not str")
try:
line.startswith(71)
except TypeError:
print("an int is not accepted either")
print(line[0] == 71)
Output
True
prefix must be bytes, not str
an int is not accepted either
True
How It Works
Correct call. A bytes prefix matches the request method.
str rejected. Text and bytes are different types, so "GET" raises TypeError.
int rejected. 71 is the code for G, but startswith() only takes bytes or a tuple of bytes.
Compare the first byte. Indexing returns an int, so line[0] == 71 is the way to test a single byte value.
Frequently Asked Questions
Open the file in "rb" mode, read a few bytes, and call header.startswith(b"\x89PNG") or pass a tuple of signatures.
Yes. Pass a tuple: data.startswith((b"GIF87a", b"GIF89a")). A list raises TypeError.
The prefix is a str. Bytes methods need bytes-like arguments, so write b"abc".
No. Use data[:1] == b"\x00" or data[0] == 0 (after checking that data is not empty).
Yes. Compare data.lower().startswith(b"get") if you want to ignore ASCII case.