A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-ways-to-count-number-of-substring-in-string/ below:

Python - Ways to Count Number of Substring in String

Python - Ways to Count Number of Substring in String

Last Updated : 12 Jul, 2025

Given a string s, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use methods like count().

Using str.count()

count() method returns the number of non-overlapping occurrences of a substring in the string.

Python
# Define the input string and the substring to count
s = "hellohellohello"
sub = "hello"

# Use the count() method to find the number of occurrences of the substring
c = s.count(sub)
print(c) 

Explanation:

Using a For Loop with String Slicing

A for loop can iterate through the string, using slicing to check for the occurrence of a substring. For example, using s[i:i+len(substring)] inside the loop allows for comparing each slice of the string to the target substring

Python
s1 = "hellohellohello"
sub = "hello"

# Initialize count to zero
cnt = 0

# Iterate through the string to check for the substring
for i in range(len(s) - len(sub) + 1):
    if s[i:i + len(sub)] == sub:  # If substring matches, increment count
        cnt += 1
print(cnt)  

Explanation:

Using List Comprehension

Generate a list of indices where the substring starts and count its length.

Python
# Input string and substring to count
s = "hello world, hello universe"
sub = "hello"

# Count occurrences of the substring using a generator expression
c = sum(1 for i in range(len(s) - len(sub) + 1) if s[i:i + len(sub)] == sub)

print(c) 

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4