Overview
- The index() method of bytearray class in Python returns the position at which a subsequence is found in a bytearray.
- The index() method and the find() method are similar, but the index() method raises a ValueError when the given subsequence is not found in the bytearray.
Example:
# Example Python program that gets the
# index of a given subsequence from a Python
# bytearray
ba = b"Between the woods and frozen lake"
pos = ba.index(b"woods")
print("Subsequence found at position:")
print(pos)Output
Subsequence found at position:
12Example
# Example Python program that raises an
# exception when a subsequence is not found
# in a Python bytearray
fromAPoem = b"A poem lovely as a tree."
pos = fromAPoem.index(b"Plant")
print(pos)Output
Traceback (most recent call last):
File "/Users/vinodh/PythonProgs/ba_index_raise.py", line 6, in <module>
pos = fromAPoem.index(b"Plant")
^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: subsection not found