all Python 3Byte sequencesfunction
bytearray.index
bytearray — search
Like find, but raises ValueError if not found.
Syntax
ba.index(...)
Prefer index when a missing needle means the data is broken: it raises ValueError on the spot, whereas find's -1 tends to slip downstream and corrupt a slice. The argument may also be a plain int in range 0-255, which searches for that single byte — handy, since ba[i] already yields an int rather than bytes.
Examples
print(bytearray(b'banana').index(b'na')) # → 2
print(bytearray(b'banana').index(ord('n'))) # → 2
print(bytearray(b'banana').index(b'na', 3)) # → 4
print(bytearray(b'banana').find(b'x')) # → -1
print(bytearray(b'banana').index(b'x')) # → ValueError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy