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 substring are there in the string (including overlapping cases). Let’s discuss a few methods below.
Method #1: Using re.findall()
# 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) |
chevron_right
filter_none
Output:
Number of substrings 0
Method #2: Using re.finditer()
# 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) |
chevron_right
filter_none
Output:
Number of substrings 0
Method #3: Using startswith()
# 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) |
chevron_right
filter_none
Output:
Number of substrings 4
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.