Python - Find index of first occurrence of search string in a String
Find index of first occurrence of search string in a string
To find the index of first occurrence of a search string in a given string in Python, call find() method on the string and pass the search string as argument. The method returns an integer representing the index.
The syntax to find the index of first occurrence of search string search
in the string x
is
x.find(search)
Examples
1. Find index of first occurrence (string contains search string)
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)
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 search string)
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)
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.