Sling Academy
Home/Python/Python: 5 ways to check if a string contains a substring

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

Last updated: May 25, 2023

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!

Next Article: Python: Converting a string to lowercase/uppercase

Previous Article: Python: 5 Ways to Reverse a String

Series: Working with Strings in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types