VOOZH about

URL: https://www.geeksforgeeks.org/python/python-ways-to-count-number-of-substring-in-string/

⇱ Python - Ways to Count Number of Substring in String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


Output
3

Explanation:

  • count() method counts the number of non-overlapping occurrences of the substring "hello" within the string s.
  • In this case, it returns 3 because the substring "hello" appears three times in "hellohellohello".

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


Output
3

Explanation:

  • for loop iterates through the string s, using slicing (s[i:i+len(substring)]) to extract substrings of the same length as substring and compare them.
  • If the sliced substring matches the target substring, the count is incremented, resulting in a count of 3 for the occurrences of "hello" in "hellohellohello".

Using List Comprehension

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


Output
2

Explanation:

  • Generator expression iterates through all possible starting indices in s and counts matches of sub with slices of s.
  • Range ensures slicing stays within bounds to compare each substring correctly.
Comment