
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python program to count number of substring present in string
Suppose we have a string s and a substring t. We have to count how many times t occurs in s.
So, if the input is like s = "abaabcaabababaab", t = "aab", then the output will be 3 because the substrings are ab(aab)c(aab)abab(aab).
To solve this, we will follow these steps −
- cnt := 0
- for i in range 0 to (size of s - size of t), do
- if substring of s[from index i to i + size of t - 1] is same as t, then
- cnt := cnt + 1
- if substring of s[from index i to i + size of t - 1] is same as t, then
- return cnt
Example
Let us see the following implementation to get better understanding
def solve(s, t): cnt = 0 for i in range(0, len(s) - len(t) + 1): if s[i:i + len(t)] == t: cnt = cnt + 1 return cnt s = "abaabcaabababaab" t = "aab" print(solve(s, t))
Input
"abaabcaabababaab", "aab"
Output
3
- Related Articles
- Program to count number of distinct characters of every substring of a string in Python
- Python Program to check if a substring is present in a given string.
- Check if substring present in string in Python
- Count number of Distinct Substring in a String in C++
- Python program to count the number of spaces in string
- Python Program to Count Number of Lowercase Characters in a String
- Golang Program to Count number of lines present in the file
- Count Number of Lowercase Characters in a String in Python Program
- Java program to check if a Substring is present in a given String
- C# program to check if a Substring is present in a Given String
- Program to find minimum number of operations required to make one string substring of other in Python
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- Program to count number of elements present in a set of elements with recursive indexing in Python
- Python program to count number of vowels using set in a given string
- Program to count k length substring that occurs more than once in the given string in Python

Advertisements