Python: Check if String Contains Substring

In this tutorial, we are going to learn ways to check if String contains a Substring in Python. Let’s dive in.

1: Using the in operator

The easiest and quickest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. The in operator returns a Boolean response and can be used as follows:

fullString = "Codeforgeek"
subString = "code"

if subString in fullString:
    print "Found the substring!"
else:
    print "Substring not present in the string!"

The in operator also works well with checking the items in the list.

2: Using the String.find() function

We can use the find() method provided by the Python to check if the substring present in the string. If the match is not found using the find() method, it returns -1, otherwise it returns the left-most index of the substring in the string. Here is the example code.

fullString = "Codeforgeek"
subString = "code"

if fullString.find(subString) != -1:
    print "Found!"
else:
    print "Not found!"

If you like to find the position of a string as well along with the existence check, do check out the next approach.

3: Using the String.index() function

We can use the index method provided by Python to check the first occurrence of a substring in a string. If the substring is not found, a ValueError exception is thrown, which needs to be handled with a try-except-else block to avoid a program crash.

fullString = "Codeforgeek"
subString = "code"

try:
    fullString.index(subString)
except ValueError:
    print "Not found!"
else:
    print "Found!"

This method returns the position of a substring hence use it if you want to find the position of a substring along with the existence.

4: Using the Regular Expression

You can use the search() method provided by the Python re package to perform regular expression search. This can be useful for complex searches such as checking case sensitiveness, etc. Here is the code to perform the regular expression search.

from re import search

fullString = "Codeforgeek"
subString = "code"

if search(substring, fullstring):
    print "Found!"
else:
    print "Not found!"

Let us know which way is your favorite to check if a string contains substring in python.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 299