7 Methods to Check If a Python String Contains A Substring?

There are a lot of things you can do with Python. Today we dive into an essential topic about using different methods to check if a string is a substring of another one in Python.

We will discuss seven techniques to determine whether a string contains a substring or not. Once you learn the concept, it will come in handy for you in your python programming endeavors.

After going through each method, I have created a related questions section to answer some special cases for using string contains methods.

Below are the 7 approaches to control if a python string is part of another string or not.

1 – Using in Operator:

In python, in is a membership operator. It checks whether a particular item you are searching for exists in the sequence or not. The sequence can be in the form of strings, List, Tuples. But in this article, we specifically talk about strings.

Suppose we have two variables, a(substring) and b(main-string), we will check if a is in b or not.

While using the in operator we get either of two results.

  • in operator offers a faster execution time than any other method.
  • If “substring” is present in the main string, the output is “True”
  • if “substring” doesn’t exist in the main string, the output is “False”.

Code:


main_str="Python does not require a compiler"
sub_str = "compiler"

if sub_str in main_str:
	print(True)
else:
	print(False)

Output:


True

Note: At the backend of the “in” functions, the method __contains__, is called when the in operator executes.

Code:


main_str="Python does not require a compiler"
sub_str = "compiler"
#while using "in" , __contains__ method is called internally
print(main_str.__contains__(sub_str))

True

Of course, in is more readable and beginner-friendly, so it’s appropriate to use the in operator for this task.

2 – find() method:

find() method execute differently than other methods. It outputs in the form of an int (i.e., index of the pattern).

  • find() gives the index of the substring present in the main string.
  • If the substring is present in main-string, it outputs 0 or higher, as index starts with 0
  • If the substring is not found, find() method outputs “-1”, indicating that no substring is found.(there is no index below 0)

Code:


#find gives us the index of sub_str.

main_str = "Django is a high-level Python Web framework"
sub_str = "framework"

if main_str.find(sub_str)== -1:  #-1 means if not present
	print(False)
else:
	print(True) #otherwise 


print(f"the index of substring present in main_str is {main_str.find(sub_str)}")
# this will find the index of substring
print(main_str.index("framework")) #actual index of "development" is same as sub_str

Output:


True
the index of substring present in main_str is 34
34

3 – Using Regular expression:

A regular expression (known as regex) is used to search for patterns in different sequences.

We can also control if a specific character(#, %, @, ! etc.) is present in the string or not with this method.

  1. re.match(pattern,iterable):
    • Re.match takes in two parameters. First is the pattern(substring) you are searching for, and the second is the iterable(main string).
    • The re.match() only searches for the first occurrence of a substring in the main string.
    • If the substring is found in the middle of the main_string, match method will not match, it’s the major drawback of using re.match for this task.

    Code:

    
    import re #re is the acronym of Regular expression
    
    main_str = "AWS stands for amazon web services"
    sub_str = "AWS"
    
    if re.match(sub_str,main_str):
    	print(True)
    else:
    	print(False)
    
    another_str ="amazon"
    if re.match(another_str,main_str):
    	print(True)
    print(False)   #using False outside the loop means "if nothing is True print False"
    
    

    Output:

    
    True
    False
    
    
  2. re.search(pattern,iterable):

    re.search(), regular expression function can be used to solve the above problem.

    Here, instead of searching only for the first occurrence, it will iterate over the full sequence

    Let’s see how it works:

    Code:

    
    #2nd method
    
    import re  #re is regular expression
    def check_sub():
    	main_str = "Machine Learning is the best use of Python"
    	sub_str = "Python"
    
    	if re.search(sub_str,main_str):          #re.search(pattern,iterable)
    		print(f"{sub_str} is present in [main_string] ")
    	else:		
    		print(f"{sub_str} not found")
    
    check_sub() #ending
    
    

    Output:

    
    Python is present in [main_string]
    

4 – str.index():

str.index() is another special method used to solve this problem.

  • It has 3 parameters.
  • str.index()method throws a ValueError exception if the substring is not found in the main string.
  • This is the reason why we use exception handling in the example code below. (try, except block).

Code:


#using str.index method
main_str = "pygame is python game development framework"
sub_str = "game development"

#use of exception handling
try:
	if main_str.index(sub_str):
		print("sub_str found in [main_str]")
except:
	print("sub_str not found in [main_str]")

Output:


sub_str found in [main_str]

What if we don’t use try/except?

Code:


main_str = "pygame is python game development framework"
sub_str = "gaming" #not present in main_str
#not using try-except
if main_str.index(sub_str):
	print("sub_str found in [main_str]")
else:
	print("sub_str not found in [main_str]")

Output:


ValueError: substring not found

A value error is raised, so this method is not usable without exception handling.

5 – using operator:

The operator is mostly used for mathematical operations.

Operator method is an obscure method and is not used frequently for this purpose

Example:

operator.add(x,y) → it will perform x+y, you can read more about it here.

  • contains()can be used for b in a testing.
  • It takes two parameters to operate.
  • The first parameter is the main string, and the second one is the
  • It tests the outcome of sub_str in main_string and returns a boolean value.

Code:


#importing
import operator

main_str = "Machine Learning is the best use of Python"
sub_str = "Learning"

#check if a substring is present or not
print(operator.contains(main_str,sub_str)) 

Output:


True

6 – Using “for Loop”:

Another method to look for a string in another one is using a “for loop”. For loop is used to iterate over sequences (like string, list, tuples, etc.).

  • First, we split() the string using split() function.
  • Then we iterate over the main string word by word.
  • Check if the substring matches as a part of the main string.
  • If it matches, we can do whatever we aim to do.
  • If not matches, then there is no substring.

Code:


# method using a for loop

main_str = "Space smells like seared steak."
sub_str = "smells"

print(main_str.split()) #split() method results a list of words
print("\n")

for i in main_str.split():
	if i==sub_str:
		print(True,"- substring matched") #True if string matches
	else:
		pass #will do nothing if substring not matches

Output:


['Space', 'smells', 'like', 'seared', 'steak.']

True - substring matched

7 – count() method:

count()method returns an integer indicating the total occurrences of the substring in the main string.

  • If substring doesn’t exist, it returns 0.
  • We can build the logic by using an if statement.

Code:


main_str = "the creator of python is Guido van Rossum"
sub_str = "Guido"

#count() method give the number of occurrences

print(f"the number of occurrences is {main_str.count(sub_str)}")
#we can use this in if statements here.
print("\n")

if main_str.count(sub_str) >0: #if present the count will be greater
	print("sub_str found :)")
else:
	print("sub_str not found! :(")

Output:


the number of occurrences is 1

sub_str found :)

Questions

Q-How to check if a string contains another string while ignoring case (case-insensitive)

The easiest way is to convert both the string into either lowercase or uppercase.

  • Using lower() or str.upper()

Code:


main_str = "PythoN iS Not a sNakE" #string with both upper and lower case
sub_str = "snAke"

#both strings converted to lowercase
if sub_str.lower() in main_str.lower():
	print(True)
else:
	print(True)

Output:


True

Q- How to check if a string contains numbers in python

isdigit is another string method useful in checking if a string contains numbers.

isdigit() is a method you can apply to a string to check if it contains a number.

  • It outputs a boolean value. (True or False).
  • We will use a for loop to iterate each element in the main string.
  • And control if it’s a digit or not.

Code:


print("7".isdigit()) #this is how we can use isdigit()

#creating a function
def check_digit():
	main_str = "i have 4 books and 3 pens"
	#iterating
	for i in main_str :
		#check if i is a digit
		if i.isdigit():
			print(True, end='-'+ f"the digit is {i}")
			print('\n')
		else:
			pass

check_digit()

Output:


True
True-the digit is 4
True-the digit is 3

Q- How to check if a string contains letters

  • You can also solve this simple problem, using isalpha()
  • isalpha() is a string method checks if it contains alphabet or not
  • Outputs either True or False

code:


#we can similarly use alpha as we used isdigit()

main_str = "python 3"

for i in main_str.replace(" ",''):
# we replace spaces between the main_str spaces are not alpha hence output False :)
	if(i.isalpha()):
		print(f"alphabet found -- {i}")
	else:
		print(f"digit found -- {i}")

Output:


alphabet found -- p
alphabet found -- y
alphabet found -- t
alphabet found -- h
alphabet found -- o
alphabet found -- n
digit found -- 3

Q- How to check if a string contains certain characters?

We can use re.compile()” method to find special characters in the main string.

  • re.compile()” will compile and treat each character in the substring as an
  • Then we searched for each particular character that will be searched for in the main string.

Code:

,
import re  #re= regular expression

#creating a function to check for special characters
def check_special():

	main_str = "i love@_! programming#$" #string containing special characters

	#compile method will treat each special character as an object.
	sub_str = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
	
	if sub_str.search(main_str) ==None:
		print(" special character not found")
	else:
		print("special character found!")

#calling function
check_special() 

Output:


special character found!

Q- How to control if a string contains multiple strings?

  • First, we will create a list of substrings that we want to check if each one exists inside the main string or not?
  • We will use all() function and control if each substring found in the main string.

Code:


main_str="Python does not require a compiler"
#checking multiple substring in main_string
sub_str = ['Python','require',"compiler"]

if all(x in main_str for x in sub_str):
	print(True)
else:
	print(False)

Output:


True

Q- How to control the number of substrings that exist in the main string?

  • findall()from the regex module can be used for this purpose.
  • findall(pattern, iterable) takes in two parameters.
  • findall() results in a list of all the substrings that is found in the main string.
  • Then we can apply the len()” function to check the length of the list.
  • The length of the list will give us the number of occurrences of the substring.
  • Answer found 🙂

Code:


import re #regular expression

main_str = "But you never know now do you now do you now do you."
sub_str = "you" #find you's in the main string

# re.findall(pattern,iterable)
a =re.findall(sub_str,main_str) # outputs a list
print(a)

print("\n") #  \n use to create a line space
print(f"the sub_str occurs {len(a)} times") # using f-strings

Output:


['you', 'you', 'you', 'you']