Python Practice › String Programs › Program 5
Count occurrences of a substring
Write a Python program to count how many times a substring occurs in a string.
Input
text = "the cat sat on the mat with the hat", sub = "the"
Output
3 4
Approach
- Use
str.count().
Solution
text = "the cat sat on the mat with the hat"print(text.count("the"))print(text.count("at"))Output
3 4
Line by line
Line 2
count() counts non-overlapping occurrences.
Note
Because matches do not overlap, "aaaa".count("aa") is 2, not 3.
Learn the concept
New to this topic? Read the lesson, then come back.