How to find if a string contains the substring in Python ?

A substring is a small portion of the string. When working with strings, a common use case is to check if a given substring is present in a string or not. Python supports various built-in functions which can be used to find if a string contains the given substring or not.

In today’s short tutorial let’s learn different ways of checking if a string contains the substring in Python.

Note: In certain cases, the kind of strings you get to work on is not in your control. You might get None object or an empty string. Not all the methods discussed below will work in those cases. Considering that we have discussed possible ways to work around that problem.

Method 1: Using in operator

The easiest way of checking if a string contains the substring is by using the Python’s in operator. Refer to the below example.

my_string="Welcome to pythonhowto"

if "python" in my_string:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

However, note that if the string is a None object, it throws an error. Refer to the below example.

my_string=None

if "python" in my_string:
    print("substring is present")
else:
    print("substring is not present")

Output:

Traceback (most recent call last):
File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Checking_if_subarray_is_present.py", line 7, in <module>
if "python" in my_string:
TypeError: argument of type 'NoneType' is not iterable

To avoid this case, we can have an extra check to ensure there are no None objects as shown below.

my_string=None

if my_string!=None and "python" in my_string:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is not present

 

Method 2: Using contains() from the operator module

The operator module contains the function named contains() which can be used to check if a substring is present in the given string. To use that function we have to first import it using the below statement.

from operator import contains

The syntax of contains() is as follows :

contains(string,substring)

It returns

True – if the substring is present in the string.

False – if the substring is not present in the strings.

 

Let’s consider the following examples.

if contains(my_string,"python"):
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

Note that if the string is a None object, an error is thrown.

Traceback (most recent call last):
  File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Checking_if_subarray_is_present.py", line 34, in <module>
    if contains(my_string,"python"):
TypeError: argument of type 'NoneType' is not iterable

 

In such cases, we should either have an extra check to verify that the string is not None or have a try-except block to handle this error. In this example, let’s have a try-except block.

try:
    if contains(my_string,"python"):
        print("substring is present")
    else:
        print("substring is not present")
except TypeError:
    print("The string is a None object. Please pass a valid string object")

Output:

The string is a None object. Please pass a valid string object

 

Method 3: Using built-in string methods

There are many built-in methods from the string class that can be used to check if the string contains the substring.

3.1 Using string.find()

The string.find() returns the index of the occurrence of the substring within the given string. If there is no match found, -1 is returned. The syntax is as shown below.

str.find(substring, start, end)

start – This is an optional parameter. This is the starting index from which the system starts looking for the match. By default, this value is 0.

end – This is an optional parameter. This is the ending index up to which the system looks out for the match. By default, this value is the end of the string.

 

Now, let’s look at an example.

my_string="Welcome to pythonhowto"
if my_string.find("python") > 0:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

If no match is found, the find() returns -1.

my_string="Welcome to pythonhowto"

if my_string.find("code") > 0:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is not present

Note that if we have None object, an error is thrown. To avoid that, we can use the try-except block.

try:
    if my_string.find("code") > 0:
        print("substring is present")
    else:
        print("substring is not present")
except AttributeError:
    print("The object is of None type.Please provide a valid String object.")

Output:

The object is of None type.Please provide a valid String object.

 

3.2 Using string.index()

The string.index() returns the index of the first occurrence of the substring. However, if the match is not found it raises an exception. The syntax of string.index() is as follows:

string.index(substring,start,end)

start – This is an optional parameter. It indicates the index from where the search would start. By default, it is 0.

end- This is an optional parameter. It indicates the index from where the search would end. By default, it is the end of the string.

 

Let’s run string.index() on our string and check what happens.

my_string="Welcome to pythonhowto"
if my_string.index("python"):
    print("substring is present")

Output:

substring is present

If the substring is not found, it throws a Value Error exception. Refer to the below code.

if my_string.index("python"):
    print("substring is present")
else:
    print("substring is not present")

Output:

Traceback (most recent call last):
File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Checking_if_subarray_is_present.py", line 13, in <module>
if my_string.index("code"):
ValueError: substring not found

To fix this we can have a try-except block as follows:

my_string="Welcome to pythonhowto"
try:
    if my_string.index("code"):
        print("substring is present")
except ValueError:
        print("substring is not present")

Output:

substring is not present

Note that if the object is None, it throws an exception, to fix it, use the try-except block as shown below.

my_string=None
try:
    if my_string.index("code"):
        print("substring is present")
except ValueError:
        print("substring is not present")
except AttributeError:
    print("The object is of None type.Please provide a valid String object.")

Output:

The object is of None type.Please provide a valid String object.

3.3 Using string.count()

Using string.count() returns the number of occurrences of a substring in a given string.  If there are no occurrences, 0 is returned.

We can use the string.count() method to check if a string contains the substring as shown below.

my_string="Welcome to pythonhowto"
if my_string.count("python") > 0:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

Now, let’s see what happens if the string does not contain the substring.

my_string="Welcome to pythonhowto"
if my_string.count("code") > 0:
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is not present

Note that if there are None objects, we can handle it using the try-except block. Refer to the above examples for details.

Method 4: Using Regex functions

Python supports the regular expressions with a module named re. You can use some of the functions to determine if a string contains a given substring or not. To use the regex functions, we have to first import regex using the following command :

import re

Now, we can use one of the below functions.

4.1 Using re.findall()

re.findall() returns the list with occurrences of the substring.

The syntax is as follows:

re.findall(string,substring)

Let’s look at an example.

import re

my_string="Welcome to pythonhowto"
if len(re.findall('o',my_string)) > 0 :
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

Now, let’s see what happens if the string is blank.

import re

my_string=""
if len(re.findall('o',my_string)) > 0 :
   print("substring is present")
else:
   print("substring is not present")

Output:

substring is not present

However, if the string is a None object, an Attribute error is thrown. To avoid it, we can have a try except block as shown below.

import re

my_string=None

try:
    if len(re.findall('o',my_string)) > 0 :
        print("substring is present")
    else:
        print("substring is not present")
except TypeError:
    print("The object is of None type.Please provide a valid String object.")

Output:

The object is of None type.Please provide a valid String object.

 

4.2 Using re.search()

re.search() returns a match object location corresponding to the first occurrence of the match of an object.

The syntax is as follows:

re.search(string,substring)

 

Let’s try running re.search() on our string.

my_string="Welcome to pythonhowto"
if re.search('o',my_string) :
    print("substring is present")
else:
    print("substring is not present")

Output:

substring is present

If the string is a None object, Attribute Error is seen. To fix this, use the try-except block.

import re
my_string=None

try:
    if re.search('o',my_string) :
        print("substring is present")
    else:
        print("substring is not present")
except TypeError:
    print("The object is of None type.Please provide a valid String object.")

Output:

The object is of None type.Please provide a valid String object.

 

 

 

That’s all. Thank you for reading. We hope this article has been informative. Do subscribe to us for more interesting content.

If you enjoyed reading, share this article.

Anusha Pai is a Software Engineer having a long experience in the IT industry and having a passion to write. She has a keen interest in writing Python Errorfixes, Solutions, and Tutorials.

1 thought on “How to find if a string contains the substring in Python ?”

Leave a Comment