Count Substring Occurrences

Count how many times substring appears.

Logic BuildingIntermediate
Logic Building
# Take two strings
s = input("Enter string: ")
substring = input("Enter substring: ")

# Count occurrences
count = s.count(substring)
print(f"Occurrences: {count}")

Output

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

Use count() method to count occurrences.

Key Concepts:

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