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
Recommended Posts:
- Python | Ways to find nth occurrence of substring in a string
- Python | Count overlapping substring in a given string
- Python | Ways to split a string in different ways
- Python program to count number of vowels using sets in given string
- Python | Count the Number of matching characters in a pair of string
- Python | All occurrences of substring in string
- Python | Remove the given substring from end of string
- Python | Frequency of substring in given string
- Python | Get the string after occurrence of given substring
- Python | Get the substring from given string using list slicing
- Python | Check if a Substring is Present in a Given String
- Python | Check if substring present in string
- Python Program to Count ways to reach the n'th stair
- Reverse string in Python (5 different ways)
- Find length of a string in python (4 ways)
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.


