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()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:



Number of substrings 0

Method #2: Using re.finditer()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

Number of substrings 0

 
Method #3: Using startswith()

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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


Output:

Number of substrings 4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.