Python | Ways to count number of substring in string
Given a string and a substring, write a Python program to find how many numbers of substrings are there in the string (including overlapping cases). Let’s discuss a few methods below.
Method #1: Using re.findall() Method
Python3
# Python code to demonstrate # to count total number # of substring in string import re # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using re.findall res = len (re.findall( '(?= aba)' , ini_str)) # Printing result print ("Number of substrings", res) |
Method #2: Using re.finditer() Method
Python3
# Python code to demonstrate # to count total number # of substring in string import re # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using re.finditer res = sum ( 1 for _ in re.finditer( '(?= aba)' , ini_str)) # Printing result print ("Number of substrings", res) |
Method #3: Using startswith()
Python3
# Python code to demonstrate # to count total number # of substring in string # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using startswith res = sum ( 1 for i in range ( len (ini_str)) if ini_str.startswith("aba", i)) # Printing result print ("Number of substrings", res) |
Output:
Number of substrings 4
Method #4: Using count() Method
Python3
# Python code to demonstrate # to count total number # of substring in string # Initialising string ini_str = "ababababa" sub_str = 'aba' # Count count of substrings using count def Countofoccurrences(ini_str,sub_str): # Initialize count and start to 0 count = 0 start = 0 # Search through the string till # we reach the end of it while start < len (ini_str): # Check if a substring is present from # 'start' position till the end pos = ini_str.find(sub_str, start) if pos ! = - 1 : # If a substring is present, move 'start' to # the next position from start of the substring start = pos + 1 # Increment the count count + = 1 else : # If no further substring is present break # return the value of count return count # Printing result print ( "Number of substrings" , Countofoccurrences(ini_str,sub_str)) |
Output
Number of substrings 4