Related Articles

Related Articles

Python | Ways to count number of substring in string
  • Last Updated : 30 Jun, 2019

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :