Python Program to Check if a String Contains a Substring
Beginner · Strings
A substring is a part of a string, so "gram" is a substring of "programming". This program checks whether one string appears inside another and, if it does, where it starts.
Program
"programming" is found in the string It starts at index 20 Contains PYTHON, ignoring case? True
How it works
sub in textisTruewhensubappears anywhere insidetext, andFalseotherwise.text.find(sub)gives the index where the substring starts, counting from 0, or -1 if it is not there.- The check is case-sensitive: "PYTHON" is not found in "Python is fun" unless both are lower-cased first.
- An empty string counts as a substring of every string, so check that
subis not empty when it comes from the user.
Other ways to write it
Without the in operator
"pop" found at index 12
The loop slides a window the length of sub along text and compares each slice with sub, which is what in does for you behind the scenes.
Find every position
"the" appears 3 times Found at index 0 Found at index 12 Found at index 24
count() gives how many times the substring appears, and find(sub, start) begins searching at start, so the loop moves from one match to the next.
Try it yourself
Set sub to "Popular" with a capital P, run it, then change the check so it ignores case.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Count Occurrences of a Character in a String
- Search for a Word in a File
- Replace a Character in a String
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises