all Python 3Byte sequencesfunction
bytes.index
bytes — search
Like find, but raises ValueError if not found.
Syntax
b.index(...)
Choosing between index and find is a policy decision: index when a missing subsequence means broken data and failing loudly is right, find when absence is a normal case you branch on. If you wrap it in try, catch ValueError specifically, not Exception — a blanket catch would also swallow the TypeError from accidentally passing a str.
Examples
print(b'banana'.index(b'na')) # → 2
print(b'banana'.index(b'na', 3)) # → 4
print(b'banana'.index(ord('n'))) # → 2
print(b'banana'.index(b'z')) # → ValueError
print(b'banana'.find(b'z')) # → -1
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy