Count Substring Occurrences

Count how many times substring appears.

IntermediatePhase 5 - Category 5: Advanced String LogicExample 3 of 14
count-substring-occurrences.py
1# Take two strings
2s = input("Enter string: ")
3substring = input("Enter substring: ")
4
5# Count occurrences
6count = s.count(substring)
7print(f"Occurrences: {count}")

Output

Enter string: Hello Hello World
Enter substring: Hello
Occurrences: 2

What's going on

Use count() method to count occurrences.

Key Concepts:

count(substring) counts occurrences
Returns number of matches
Simple method