Check if substring present in string in Python


In python data analysis we may come across a scenario to check if a given substring is part of a bigger string. We will achieve this through the following programs.

With find

The find function finds the first occurrence of the specified value. If the value is not found then it returns -1. We will apply this function to the given string and design a if clause to find out is substring is part of a string.

Example

 Live Demo

Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Astring.find(Asub_str) == -1):
   print("Substring is not a part of the string")
else:
   print("Substring is part of the string")

Output

Running the above code gives us the following result −

Given string: In cloud 9
Given substring: cloud
Substring is part of the string
Given substring: 19
Substring is not a part of the string

With count

The method count() returns the number of elements with the specified value in a string or data collection in python. In the below program we will calculate the count of the substring and if it is greater than 0 we conclude that the substring is present in the bigger string.

Example

 Live Demo

Astring = "In cloud 9"
Asub_str = "cloud"
# Given string and substring
print("Given string: ",Astring)
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is part of the string")
else:
   print("Substring is not a part of the string")

# Check Agian
Asub_str = "19"
print("Given substring: ",Asub_str)
if (Asub_str.count(Astring)>0):
   print("Substring is a part of the string")
else:
   print("Substring is not a part of the string")

Output

Running the above code gives us the following result −

Given string: In cloud 9
Given substring: cloud
Substring is not a part of the string
Given substring: 19
Substring is not a part of the string

Updated on: 13-May-2020

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements