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 browser1# Program to find substring in a string23text = input("Enter main string: ")4sub = input("Enter substring: ")56index = text.find(sub)78if 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.