Python: 5 ways to check if a string contains a substring

Updated: May 25, 2023 By: Khue Post a comment

This succinct, practical article will walk you through several different ways to check whether a string contains a specific substring in Python. I assume you already have some basic understanding of the programming language, so I won’t waste your time by praising how powerful Python is or talking about its prolonged history. Let’s go straight to the point!

Using the “in” operator

Using in operator is the neatest and most elegant way for the task. It returns True if the substring is found and False otherwise.

Example:

my_string = "League of Legends is a fun game!"

# Using the 'in' operator
if "League of Legends" in my_string:
    print("Substring found!")
else:
    print("Substring not found!")

Output:

Substring found!

Using the str.index() method

The str.index() method returns the index of the first occurrence of the substring in the parent string. However, if the substring is not found, the method will raise a ValueError exception.

Example:

text = "Reddit and Steam are my favorite websites."

try:
    text.index("favorite")
    print("The word 'favorite' exists in the text.")
except ValueError:
    print("The word 'favorite' does not exist in the text.")

Output:

The word 'favorite' exists in the text.

Using the str.find() method

Like the str.index() method, the str.find() method returns the index of the first occurrence of a substring within a string. However, it won’t raise an exception if the substring is not found. Instead, it returns -1.

Example:

text = "CS:GO is one of the best shooting games."

if text.find("CS:GO") != -1:
    print("CS:GO is found")
else:
    print("CS:GO is not found")

Output:

CS:GO is found

Using regular expressions

Regular expressions are a powerful tool for working with strings, and the re module in Python provides powerful tools for working with regular expressions. You can use the re.search() function to search for a pattern (in the context of this article, it is a substring) within a string.

Example:

import re

my_string = "Turtles are cool!"

# Using regular expressions
if re.search("cool", my_string):
    print("Substring found!")
else:
    print("Substring not found!")

Output:

Substring found!

Using the startsWith() and endsWith() methods

This duo can help you check if a given string starts or ends with a specific substring. However, they are useless if the substring is somewhere in a string that is neither the beginning nor the end.

Example:

text = "What we don't know is unlimited."

# Check if the text starts with "What"
if(text.startswith("What")):
    print("Yes, the string starts with 'What'")
else: 
    print("No, the string does not start with 'What'")

# Check if the text ends with "turtles."
if(text.endswith("turtles.")):
    print("Yes, the string ends with 'turtles.'")
else:
    print("No, the string does not end with 'turtles.'")

Output:

Yes, the string starts with 'What'
No, the string does not end with 'turtles.'

Conclusion

We’ve gone over a bunch of solutions to determine whether a string includes a substring or not. This knowledge is useful for tasks like pattern matching, text processing, filtering data, or conditional logic based on specific substrings present within a larger string. The tutorial ends here. I don’t want it to become unnecessary long. Happy coding & enjoy your day!