all Python 3Byte sequencesfunction
bytearray.find
bytearray — search
Index of the first occurrence, or -1.
Syntax
ba.find(...)
A miss gives -1 rather than an exception, and -1 is a legal index, so ba[ba.find(b'x')] quietly hands you the last byte instead of failing. Use b'na' in ba when you only need presence; reach for find when the position itself matters. The start and end arguments merely narrow the search window — the returned index is still counted from the beginning of the bytearray.
Examples
print(bytearray(b'banana').find(b'na')) # → 2
print(bytearray(b'banana').find(b'na', 3)) # → 4
ba = bytearray(b'key: value'); print(ba[ba.find(b':') + 2:].decode()) # → value
print(bytearray(b'banana').find(b'z')) # → -1
print(bytearray(b'banana').index(b'z')) # → ValueError
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy