Python String - Find the index of first occurrence of substring
Python String - Find the index of substring
To find the position of first occurrence of a substring in a string in Python, you can use string.find() method.
index = string.find(substring, start, end)
where string
is the string in which you have to find the index
of first occurrence of substring
. start
and end
are optional and are starting and ending positions respectively in which substring has to be found.
Examples
1. Find index of substring in string
In the following example, we will take a string and try to find the first occurrence of substring prog
.
Python Program
string = 'Python programming. Network programming.'
substring = 'prog'
index = string.find(substring)
print(index)
Output
7
2. Find index of substring after a specific position
In the following example, we will take a string and try to find the first occurrence of substring prog
after position 12
in the string.
Python Program
string = 'Python programming. Network programming.'
substring = 'prog'
start = 12
index = string.find(substring, start)
print(index)
Output
28
Now it has found index of the substring that occurred for the first time after start
position.
Summary
In this tutorial of Python Examples, we learned how to find the index of substring in a string using str.find() function.