Find Substring in Python

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

BeginnerString ProgramsExample 8 of 25
find-substring.py
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.

After this program

If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.