Python bytes.startswith() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
bytes method

Definition

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)
CallWhat 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

ParameterDescription
prefixA bytes-like object, or a tuple of them. A str or int raises TypeError.
startOptional. Index where the comparison begins.
endOptional. Index where the compared slice ends.

Return Value

Return ValueDescription
TrueThe slice data[start:end] begins with prefix (or one of the tuple items).
FalseIt 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"))

How It Works

  1. Non-ASCII signature. PNG files start with the byte 0x89 followed by PNG; the escape \x89 writes that byte in the literal.
  2. Two GIF versions. The tuple accepts both GIF87a and GIF89a in a single check.
  3. Text signature. PDF files begin with the ASCII bytes %PDF- and a version number.
  4. 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.

python
packet = b"\x01\x00HELLO\x00"

print(packet.startswith(b"HELLO"))
print(packet.startswith(b"HELLO", 2))
print(packet.startswith(b"HEL", 2, 4))
print(packet.startswith(b""))

How It Works

  1. Header first. The packet begins with the two header bytes \x01\x00, so the payload is not at index 0.
  2. Skip the header. With start=2 the comparison begins at the payload and succeeds.
  3. End cuts the slice. packet[2:4] is only b'HE', too short to start with b"HEL", so the result is False.
  4. 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)

How It Works

  1. Correct call. A bytes prefix matches the request method.
  2. str rejected. Text and bytes are different types, so "GET" raises TypeError.
  3. int rejected. 71 is the code for G, but startswith() only takes bytes or a tuple of bytes.
  4. 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.

Next: bytes.strip()

Return a copy with leading and trailing bytes from a set removed (whitespace by default).

strip() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

15 people found this page helpful