Find Substring in Python

Check if a substring exists within a string and find its index.

BeginnerString ProgramsExample 8 of 25
find-substring.py
Run in browser
1# Program to find substring in a string
2
3text = input("Enter main string: ")
4sub = input("Enter substring: ")
5
6index = text.find(sub)
7
8if index != -1:
9 print(f"Substring found at index {index}")
10else:
11 print("Substring not found")

Output

Enter main string: hello world
Enter substring: world
Substring found at index 6

What's going on

We use .find() which returns the starting index of the substring or -1 if not found.