Search code snippets, questions, articles...

Check if String contains a Substring in Python

In Python, checking if a string contains a substring is easy. There are multiple solutions in order to do that. We will explain them one by one in this post.

Check if String contains a Substring in Python

To check whether a String contains a substring:

  1. Use if statement along with in operator - if "sheet" in "devsheet".
  2. If the string matches execute some code inside the if block.

Solution 1: Check substring using in operator

Python has a built-in method called "in" that can be used to check if a string contains a substring. This method is case-sensitive, so you will need to make sure that the string and substring are both in the same case.

Syntax

"Substring" in "String"

Here is an example of how to use the "in" method:

if "wor" in "hello world":
    print("matched")
else:
    print("Not matched")

Output

matched

The code is checking if the string "wor" is found in the string "hello world". If it is found, it will print "matched". If it is not found, it will print "Not matched".


Solution 2: Check Substring using find() function

Python has a built-in find() method to check if a string contains a substring or not. This method returns the index of the substring if it is found, otherwise, it returns -1.

Syntax:

String.find(Substring)

Code example:

my_str = "Devsheet"
my_substr = "sheet"

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

Output

Found

The above code example is looking for a substring within a string using the find() function. If the substring is found, it will print "Found". Otherwise, it will print "Not found".


Solution 3: Check Substring using regex(re) - search() function

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data. The Python "re" module provides regular expression support.

Here, we will learn how to use the Python regex search() function to check if a string contains a substring using regular expressions. We will use the search() function to check if a substring exists in a string and return a Boolean True/False value.

from re import search

full_string = "Devsheet"
sub_string = "hee"

if search(sub_string, full_string):
    print("Substring found")
else:
    print("Substring not found")

Output

Substring found

The above python code example above uses the re module's search function to check if a substring is found in a given string. If the substring is found, the code prints "Substring found". Otherwise, if the substring is not found, the code prints "Substring not found".


Was this helpful?
0 Comments