Python bytes.index() Method

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

Definition

bytes.index() returns the same value as find() when the needle exists: the lowest index where it starts. The difference is what happens when it is missing: index() raises ValueError with the message subsection not found.

Choose it when a missing value means the data is broken, for example a required field in a record or a signature that every valid file must contain. The exception stops bad data early instead of letting a -1 slip into later slicing.

bytes.index() is a method of the built-in bytes type: call it on a bytes object with dot notation, such as data.index(...). No import is needed, and bytearray objects have the same method.

Syntax

Arguments match find(); wrap the call in try when absence is possible.

python
pos = data.index(sub)
pos = data.index(sub, start)
pos = data.index(sub, start, end)
CallWhat it does
b"a=1".index(b"=")Returns 1.
b"a=1".index(b"#")Raises ValueError: subsection not found.
b"abab".index(b"ab", 1)Returns 2.
b"\x00\xff".index(255)Returns 1.

Catch ValueError itself; do not rely on the exact message text, which is an implementation detail.

Method signatures
python
bytes.index(sub[, start[, end]])
# sub: bytes-like object or int in range(256)
# raises ValueError when sub is not found

Parameters

ParameterDescription
subThe bytes to look for, or one byte value as an int 0-255.
startOptional. Index to start searching from.
endOptional. Index to stop before; the match must fit inside.

Return Value

Return ValueDescription
intThe lowest index where sub starts.
ValueErrorRaised (not returned) when sub is not found.

Python Examples

Example 1 — Split a Record at a Required Separator

Each record must contain a | between two fields. index() finds it, and a separate lookup for an optional field shows the exception.

python
record = b"NAME:Ada|ROLE:admin"

pos = record.index(b"|")
print(pos)
print(record[:pos], record[pos + 1:])
try:
    record.index(b"EMAIL:")
except ValueError:
    print("EMAIL field is missing")

How It Works

  1. Safe to slice. Because index() either returns a real position or raises, pos can be used for slicing without a -1 check.
  2. Two fields. The bar at index 8 divides the name field from the role field.
  3. Absent field. Searching for b"EMAIL:" raises ValueError, which the except block turns into a clear message.

Example 2 — Find the Second GIF Signature in a Blob

Two GIF headers were stored back to back. Start the second search one byte after the first match to find where the second image begins.

python
blob = b"GIF89a\x01\x00GIF87a"

first = blob.index(b"GIF")
second = blob.index(b"GIF", first + 1)
print(first, second)
print(blob[second:second + 6])
print(blob.index(0x00))

How It Works

  1. First image. The blob starts with the signature, so first is 0.
  2. Move past it. Searching from first + 1 skips the first match and finds the next one at 8.
  3. Read the version. Six bytes from the second match give the full GIF87a signature.
  4. Int needle. The first zero byte is at index 7, inside the two filler bytes between the headers.

Example 3 — A Helper That Turns ValueError into None

Sometimes a caller prefers None over an exception. Catch ValueError inside a small function and compare with find().

python
def field_start(data, key):
    try:
        return data.index(key) + len(key)
    except ValueError:
        return None


msg = b"cmd=PING;seq=42"
print(field_start(msg, b"seq="))
print(field_start(msg, b"ttl="))
print(msg.find(b"ttl="))

How It Works

  1. Value offset. seq= starts at 9, and adding its length gives 13, the index of the digits.
  2. Exception handled. ttl= is absent; index() raises and the helper returns None.
  3. Compare with find(). The same search with find() returns -1 without any exception handling.

Frequently Asked Questions

ValueError, with a message like "subsection not found". Catch ValueError rather than matching the text.
Use index() when the needle must be present and its absence is an error. Use find() when absence is normal and you want to test for -1.
Yes. data.index(0) returns the position of the first zero byte, or raises ValueError if there is none.
Yes, just like find(). The returned index is still counted from the start of the whole object.
Yes. rindex() returns the last match and also raises ValueError when there is none.

Next: bytes.isalnum()

True if all bytes are ASCII letters or digits and there is at least one byte.

isalnum() →

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.

7 people found this page helpful