Finding All Occurrences of a substring in a Python string


The strings are composed of characters and initialized in the code using simple or double quotes and substring is also a character present inside a string. Python is a versatile and high-level language that can be understood easily by the user. In this article, all the occurrences of the substring are found in a string using Python language can be done with various methods. Some common methods are index() method, in the operator, find() method, and use a regular expression method.

Finding All Occurrences of a substring in a Python string

The substrings are the characters of a string and the methods to find these substrings are explained below.

Syntax

str.find(substr, initial, final)

The string to be searched is given by str using the find() function. This function has three arguments the substring, the initial value of the string as 0, and the final value can be according to the length of the string.

Approach

Approach 1 − Using try and except method

Approach 2 − Using “re” regular expression

Approach 1: Python Program to print all the occurrences of the substring using try and except method

The input string is initialized and using index() method we can iterate over each substring that is not found, a value error is raised, and prints the statement in except block.

Algorithm

  • Step 1 − The variables are defined with values as "Hello Welcome to Tutorialspoint".

  • Step 2 − The substring variables are defined with values as "l", "z" and "e".

  • Step 3 − To find the first occurrence of the substring in the string starting from the initial index using the index() method.

  • Step 4 − The for loop is used to iterate through the strings and when the substrings are present in the string, the "All strings found" statement is printed.

  • Step 5 − When the substrings are not present in the string, then "Not All strings found" statement is printed.

  • Step 6 − − Using the try and except method, the strings are checked for all possible occurrences of the substring in the string.

  • Step 7 − When the below code runs, it returns the output.

Example

#initializing the string
num = "Hello welcome to India" 

#to find the occurrence of the substring ‘l’, ‘z’, ‘e’ is initialized as substr
substr = ["l", "z", "e"] 
#trying to find the substrings using index() method
try:
   for sub in substr:
      num.index(sub)
   #this statement is printed when the substring is present in the input string
   print("All substrings found!") 
except ValueError:
   #this statement is printed when the substring is not present in the input string
   print("substrings are not found!") 

Output

substrings are not found!

Approach 2: Python Program to print all the occurrences of the substring using “re” regular expression

The Regular expression pattern is created to match all the substring lists to the input string. Then by using findall() function from the re python library to find all occurrences of the string. This expression returns true if the number of matches is equal to the length of the substring list, then false.

Algorithm

  • Step 1 − Import the required module as “re” library and define a function named all_substrings_present().

  • Step 2 − The function findall() is used as the “re” library is imported to check for substrings.

  • Step 3 − The defined function returns "true" when the substrings are matched with the strings otherwise returns "false".

  • Step 4 − Initialize the string named input_str as "Hello welcome to India" which contains a set of strings and initialize the substring in the next statement.

  • Step 5 − Use the if-else statement to verify that the substring is presented in the input_str or not.

  • Step 6 − Finally, the printing statement returns according to the condition.

Example

#importing the “re” module
import re
#defining the function with two parameters as input string and substring
def strfind(input_str, substr_list):
   # Regular expression is created and initialized as a shape
   shape = "(?=.*" + ")(?=.*".join(substr_list) + ").*"
   #using the findall() function to check for the characters in the string
   matches = re.findall(shape, input_str)

   # when the substrings are matched with the strings it returns true else false
   return len(matches) == 1
#initializing the string 
input_str = "Hello welcome to India"
#initializing the characters that need to be found in the input string
substr_list = ["l", "c", "e"]

#To check using the if else statement 
if strfind(input_str, substr_list):
#when the characters are matched this statement is printed.
   print("All substrings found!")
else:
#when the characters are not matched this statement is printed.
   print("Not all substrings found.")

Output

All substrings found!

Conclusion

The Programmer can work with the strings but dealing with the substrings will lead to some complex problems. By using various methods, we can find all the occurrences of the substrings in the given input string of characters. The output is returned based on the matching of the string values.

Updated on: 25-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements