Find Substring
Check if a substring exists within a string and find its index.
BeginnerTopic: String Programs
Python Find Substring Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# 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
Understanding Find Substring
We use .find() which returns the starting index of the substring or -1 if not found.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.