Check if a string contains a specific substring in Python

In this tutorial, we will learn how to check if a string contains a substring in Python. We can use multiple ways to accomplish the task depending on the use and type of string we are accessing. To understand this concept efficiently you must have basic knowledge of strings in Python.

How to Check if a string contains a specific substring in Python

We will be checking for a specific substring in a string in multiple ways:

  • using in
  • str.find()
  • str.index()
  • operator.contains()

using “in”

test= "check the string"

if "check" in test:
  print("check is present in test")
else:
  print("Not present")

We have a string stored in a variable named “test“, we want to find if substring “check” is present in test. Here we use in keyword to check the condition and print the respective statement. This is the easiest way to accomplish the task.

output:
check is present in test

str.find()

Let’s directly jump on to an example to understand the concept.

test= "check the string"

if test.find("check")>=0:
  print("check is present in test")
else:
  print("Not present")

find() is a predefined-function, it returns the first occurrence of the substring if present. It returns -1 if the substring is absent in the main string.

output:
check is present in test

str.index()

This method resembles a lot of the previous one. But this method doesn’t return -1 when the required substring is absent in the main string.
This method throws an error whenever it fails to find the required string in the main string. So, while dealing with this function we have to use a try-except block.

test= "check the string"

try :
  yes=test.index("the")
  print(f"check is present in test at {yes}")
except:
  print("Not present")

this function returns the first occurrence of the substring if present.

output:
check is present in test at 6

operator.contains()

This is a rarely used method. In this method, we use the operator module.

import operator as os
test= "check the string"

if os.contains(test,"is"):
  print("YES")
else:
  print("NO")
output:
NO

This method takes two arguments, the main string and the required substring.

Leave a Reply

Your email address will not be published. Required fields are marked *