Count Substring Occurrences
Count substring occurrences with Python str.count. Students test absent and empty patterns and distinguish nonoverlapping matches from overlapping positions.
1# Take two strings2s = input("Enter string: ")3substring = input("Enter substring: ")45# Count occurrences6count = s.count(substring)7print(f"Occurrences: {count}")
Output
Enter string: Hello Hello World Enter substring: Hello Occurrences: 2
In this one
- Count nonoverlapping matches
- Recognize empty-pattern rules
- Retain exact case
How it works
- 1
Read source and substring.
- 2
Call s.count(substring).
- 3
Print the returned occurrence count.
Edge cases
What is aa counted in aaaa?
What is aa counted in aaaa?
Two nonoverlapping matches.
What if the pattern is empty?
What if the pattern is empty?
The result is len(s) + 1.
What's going on
s.count(substring) returns how many nonoverlapping literal matches occur. Neither source text nor matching rules are normalized.
For aaaa and aa, the answer is two, not three overlapping positions. An absent pattern gives zero. The empty pattern has a special count of len(s) + 1, representing insertion boundaries, so a practical search form may need to disallow it.
What is aa counted in aaaa? Two nonoverlapping matches.
What if the pattern is empty? The result is len(s) + 1.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Is matching case-sensitive?
Pick an answer to check it.
Question 2
What is aa counted in aaaa?
Pick an answer to check it.
Questions people ask
What is aa counted in aaaa?
Two nonoverlapping matches.
What if the pattern is empty?
The result is len(s) + 1.
Is matching case-sensitive?
Yes.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum