Python: Check if String Contains Substring

Python: Check if String Contains Substring

In this guide, we'll take a look at how to check if a string contains a substring in Python. As usual, each approach we'll cover has different pros and cons.

The in Operator

The easiest 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. It returns a Boolean (either True or False). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring:

fullstring = "StackAbuse"
substring = "tack"

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

This operator is shorthand for calling an object's __contains__ method, and also works well for checking if an item exists in a list. It's worth noting that it's not null-safe, so if our fullstring was pointing to None, an exception would be thrown:

TypeError: argument of type 'NoneType' is not iterable

To avoid this, you'll first want to check whether it points to None or not:

fullstring = None
substring = "tack"

if fullstring != None and substring in fullstring:
    print("Found!")
else:
    print("Not found!")

The String.index() Method

The String type in Python has a method called index() that can be used to find the starting index of the first occurrence of a substring in a string.

If the substring is not found, a ValueError exception is thrown, which can to be handled with a try-except-else block:

fullstring = "StackAbuse"
substring = "tack"

try:
    fullstring.index(substring)
except ValueError:
    print("Not found!")
else:
    print("Found!")

This method is useful if you need to know the position of the substring, as opposed to just its existence within the full string.

The String.find() Method

The String type has another method called find which is more convenient to use than index(), because we don't need to worry about handling any exceptions.

If find() doesn't find a match, it returns -1, otherwise it returns the left-most index of the substring in the larger string.

fullstring = "StackAbuse"
substring = "tack"

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

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

If you'd prefer to avoid the need to catch errors, then this method should be favored over index().

Regular Expressions (RegEx)

Regular expressions provide a more flexible (albeit more complex) way to check strings for pattern matching. Python is shipped with a built-in module for regular expressions, called re. The re module contains a function called search(), which we can use to match a substring pattern:

from re import search

fullstring = "StackAbuse"
substring = "tack"

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

This method is best if you are needing a more complex matching function, like case insensitive matching. Otherwise the complication and slower speed of regex should be avoided for simple substring matching use-cases.

About the Author

This article was written by Jacob Stopak, a software consultant and developer with passion for helping others improve their lives through code. Jacob is the creator of Initial Commit - a site dedicated to helping curious developers learn how their favorite programs are coded. Its featured project helps people learn Git at the code level.

Last Updated: July 14th, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Jacob StopakAuthor

Jacob Stopak is a software developer and creator of InitialCommit.io - a site dedicated to teaching people how popular programs are coded. Its main project helps people learn Git at the code level.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Better understand your data with visualizations

    With over 330+ pages, you'll learn the ins and outs of visualizing data in Python with popular libraries like Matplotlib, Seaborn, Bokeh, and more.

    © 2013-2021 Stack Abuse. All rights reserved.