Python – Find Index of First Occurrence of Substring in String

Find Index of First Occurrence of Substring in String

To find the index of first occurrence of substring in string in Python, call find() method on the string and pass the substring as argument. The method returns an integer representing the index.

The syntax to find the index of first occurrence of substring search in the string x is

x.find(search)

Examples

1. Find index of first occurrence (string contains substring)

In the following program, we take a string x, and a search string search. The values of x and search are such that x contains search. So, find() method must return the index of first occurrence of search in x.

Python Program

x = 'apple is red. some red apples are ripen.'
search = 'red'

index = x.find(search)

print('Index :', index)
Run

Output

Index : 9

Explanation

apple is red. some red apples are ripen.
         red   <- first occurrence
0123.. ..9 is the index of first occurrence

2. Find index of first occurrence (string does not contain substring)

In the following program, we take a string x, and a search string search. The values of x and search are such that x does not contain search. So, find() method must return -1.

Python Program

x = 'apple is red. some apples are green.'
search = 'yellow'

index = x.find(search)

print('Index :', index)
Run

Output

Index : -1

Summary

In this tutorial of Python Examples, we learned how to find the index of first occurrence of a search string or substring in a string using str.find() method, with the help of well detailed examples.