The find() method of bytearray class in Python

The find() method of bytearray class in Python finds the position of a specified subsequence from the whole bytearray or between specified positions.

Bytearray Updated 13 Nov 2025 1 min read

Overview

• For a given subsequence, the find() method of bytearray class in Python returns the index of its first occurrence.
• When a range of positions is provided by specifying the positions “after” and “before”, the find() method returns the index of the first occurrence within this range.
• When no occurrence of the subsequence is found the find() method returns -1.

Example 1 - Find the position of a subsequence in a bytearray

python
# Example Python program that finds the

            # first occurrence of a subsequence from a bytearray

# Create a bytearray

            buffer = bytearray(b"if it was so, it might be")

# The type of subsequence is bytes

            subsequence = b"it"

# Find the first occurence of a substring

            pos = buffer.find(subsequence)

print("Position of the subsequence in the bytearray:")

            print(pos)

Output

Output
Position of the subsequence in the bytearray:

            3

Example 2 - Find a subsequence in a bytearray between a range of positions

python
# Example Python program that finds the

            # occurrence of a subsequence within a given range

            # of positions after and before

buffer = bytearray(b"I knew who I was this morning, but I have changed")

            sequence2Find = bytearray(b"I")

            after = 5

            before = 15

# Find the position of a subsequence between the positions after

            # and before

            pos = buffer.find(sequence2Find, after, before)

            print("Subsequence position between index {} and {}:".format(after, before))

            print(pos)

# Find the position of a subsequence in the slice[15, len(buffer)]

            after = 15

            pos = buffer.find(sequence2Find, after)

            print("Position of the subsequence after index {}:".format(after))

            print(pos)

Output

Output
Subsequence position between index 5 and 15:

            11

            Position of the subsequence after index 15:

            35