Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Count Substring Occurrences

Count substring occurrences with Python str.count. Students test absent and empty patterns and distinguish nonoverlapping matches from overlapping positions.

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

In this one

  • Count nonoverlapping matches
  • Recognize empty-pattern rules
  • Retain exact case

How it works

  1. 1

    Read source and substring.

  2. 2

    Call s.count(substring).

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