Python - Possible Substring count from String


This article we will learn about various methods using which a substring can be counted inside the given string. While working with python you may have come to a scenario when you need to check a given word has occurred how many times in the sentence or any string, so to get the count of substring inside the larger main stirring we will see some programs.

Method 1: Using the Count Method

This is a simple and easy built-in method in the python which allows us to count the substring inside the main string. Its time complexity is O(n).

Example

def count_substr_possible(str, substr):
   count = str.count(substr)
   return count
str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

Output

Substring count is: 3

Explanation

Here in the function we pass the string and substring which will be counted and assign the substring into the count function of string. This count() method will return us the total number of occurrences. In the string “soneduonempaone”, substring “one” has occurrence of 3 so result will come out as 3, which is the total count of substring inside the string.

Method 2: Using Regular Expressions

This method allows us to work with string, like substring matching and counting. This also has the feature of finding advanced pattern matching.

Example

import re

def count_substr_possible(str, substring):
   count = len(re.findall(substring, str))
   return count
str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

Output

Substring count is: 3

Explanation

Here in the program, we import the regular expression library and using the final function from the ‘re’ we find all occurrences of the substring within the string. Findcall() function returns the list of matched substring and using the len() function we find the length of the list which will come out as total occurrences of substring within the main string.

Method 3: Using Loop and Find() Function

In this method we iterate over the string given and using the string.find() function we will find the occurrences of the substring.

Example

def count_substr_possible(str, substr):
   count = 0
   index = 0

   while index != -1:
      index = str.find(substr, index)
      if index != -1:
         count += 1
         index += 1

      return count

str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

Output

Substring count is: 1

Explanation

In the above program we create two variable count and index, where count is initialized to 0 as initially 0 substring count will be there. And we will check using the find() function to search for the substring occurrence, starting from the initial index until it returns -1. If the occurrence is there like when the index is not -1 then we increment the count as one.

Method 4: Using Comparison and Slicing

Using this method, we perform the slicing and comparison operation to count the total occurrences of substring inside the string.

Example

def count_substr_possible(str, substr):
   count = 0
   sub_len = len(substr)

   for i in range(len(str) - sub_len + 1):
      if str[i:i + sub_len] == substr:
         count += 1

      return count

str="soneduonempaone"
substr="one"
print("Substring count is:",count_substr_possible(str, substr))

Output

Substring count is: 0

Explanation

Same as method 4 example we will create a count variable initial value as 0 which will keep count of total occurrences of substring. We will traverse over the string starting from the 0 to length of string and we will use slicing operation of substring starting from the current position i.

Example

from itertools import combinations

def count_substr_possible(str, substr):
   count = 0
   sub_len = len(substr)

   for length in range(sub_len, len(str) + 1):
      for i in range(len(str) - length + 1):
         sub = ''.join(str[i:i+length])
         if sub == substr:
            count += 1

   return count

str = "soneduonempaone"
substr = "one"


print("Substring count is:",count_substr_possible(str, substr))

Output

Substring count is: 3

Explanation

Here in the program we imported the combinations from the itertools. Our function named count_substr_possible takes two parameters as string and substring. Using two nested loops we will generate combinations of characters from the string, the outer loop will traverse from the length of substring to length of larger string to generate the different length of substrings. Then we will compare the substring using equality sign, if they are equal then we will increment into the count variable.

So, we saw some methods using which we can find the total number of substrings in the larger string. We saw four different methods to solve the problem using the python language. Among all four methods string.count() method has a very simple and efficient approach of solution whereas regex expression matching provides a very efficient approach of finding complex pattern matching scenarios. Slicing and comparison also provide us with a very simple method to count the substring occurrences. So, you can choose any of the methods based on requirement and ease of use but having ideas about different approaches can help in better learning.

Updated on: 13-Oct-2023

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements