Count occurrences of a substring

EasyString Programs · 5 of 106

Write a Python program to count how many times a substring occurs in a string.

Advertisement
Input
text = "the cat sat on the mat with the hat", sub = "the"
Output
3
4

Approach

  1. Use str.count().

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs