Editor

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

check_substring.py
text = "Python is a popular programming language" # or: text = input("Enter a string: ")
sub = "programming" # or: sub = input("Enter the text to look for: ")
if sub in text:
print(f'"{sub}" is found in the string')
print("It starts at index", text.find(sub))
else:
print(f'"{sub}" is not found in the string')
# The check is case-sensitive, so compare lower-case copies to ignore case
print("Contains PYTHON, ignoring case?", "PYTHON".lower() in text.lower())
Output
"programming" is found in the string
It starts at index 20
Contains PYTHON, ignoring case? True

How it works

  1. sub in text is True when sub appears anywhere inside text, and False otherwise.
  2. text.find(sub) gives the index where the substring starts, counting from 0, or -1 if it is not there.
  3. The check is case-sensitive: "PYTHON" is not found in "Python is fun" unless both are lower-cased first.
  4. An empty string counts as a substring of every string, so check that sub is not empty when it comes from the user.

Other ways to write it

Without the in operator

Without the in operator
text = "Python is a popular programming language"
sub = "pop"
found_at = -1
for i in range(len(text) - len(sub) + 1):
if text[i:i + len(sub)] == sub:
found_at = i
break
if found_at != -1:
print(f'"{sub}" found at index {found_at}')
else:
print(f'"{sub}" not found')
Output
"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

Find every position
text = "the cat and the hat and the bat"
sub = "the"
print(f'"{sub}" appears', text.count(sub), "times")
start = text.find(sub)
while start != -1:
print("Found at index", start)
start = text.find(sub, start + 1) # search again after this match
Output
"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.

All Python programs · CBSE class 12 practical file · Python exercises