Home Python Bytes Methods index() Python bytes.index() 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.
pos = data.index(sub)
pos = data.index(sub, start)
pos = data.index(sub, start, end) Call What 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 bytes.index(sub[, start[, end]])
# sub: bytes-like object or int in range(256)
# raises ValueError when sub is not found Parameters Parameter Description sub The bytes to look for, or one byte value as an int 0-255. start Optional. Index to start searching from. end Optional. Index to stop before; the match must fit inside.
Return Value Return Value Description int The lowest index where sub starts. ValueError Raised (not returned) when sub is not found.
Python Examples 1. Required separator 2. Find the second occurrence 3. Wrap index() in a helper 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.
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") 8
b'NAME:Ada' b'ROLE:admin'
EMAIL field is missing How It Works Safe to slice. Because index() either returns a real position or raises, pos can be used for slicing without a -1 check.Two fields. The bar at index 8 divides the name field from the role field.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.
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 First image. The blob starts with the signature, so first is 0.Move past it. Searching from first + 1 skips the first match and finds the next one at 8.Read the version. Six bytes from the second match give the full GIF87a signature.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().
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 Value offset. seq= starts at 9, and adding its length gives 13, the index of the digits.Exception handled. ttl= is absent; index() raises and the helper returns None.Compare with find(). The same search with find() returns -1 without any exception handling.Frequently Asked Questions What error does bytes.index() raise? ValueError, with a message like "subsection not found". Catch ValueError rather than matching the text.
Should I use index() or find()? 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.
Can index() search for an int? Yes. data.index(0) returns the position of the first zero byte, or raises ValueError if there is none.
Does index() accept start and end? Yes, just like find(). The returned index is still counted from the start of the whole object.
Is there a version that searches from the right? 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 Developer, cloud engineer, and technical writer
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
Helpful Share Copy link Suggestion