Find Substring

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

PythonBeginner
Python
# Program to find substring in a string

text = input("Enter main string: ")
sub = input("Enter substring: ")

index = text.find(sub)

if index != -1:
    print(f"Substring found at index {index}")
else:
    print("Substring not found")

Output

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

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