Python – Find the index of first occurrence of substring in a String

Python String – Find the index of first occurrence of substring

To find the position of first occurrence of a string, 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.

Example 1: Find index of First Occurrence of Substring

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)
Run

Output

7

Example 2: Find index of First Occurrence 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)
Run

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.