Python: Count occurrences of a substring in a string
Count substring occurrences in string.
Write a Python program to count occurrences of a substring in a string.

Sample Solution:
Python Code:
# Define a string 'str1' with a sentence.
str1 = 'The quick brown fox jumps over the lazy dog.'
# Print an empty line for spacing.
print()
# Count and print the number of occurrences of the substring "fox" in the string 'str1'.
print(str1.count("fox"))
# Print an empty line for spacing.
print()
Sample Output:
1
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to count the occurrences of a specified substring in a string using the str.count() method.
- Write a Python program to implement a function that iterates over a string and manually counts overlapping occurrences of a substring.
- Write a Python program to use regular expressions to find and count all instances of a substring in a given string.
- Write a Python program to count the frequency of a substring in a string recursively.
Python Code Editor:
Previous: Write a Python program to display a number in left, right and center aligned of width 10.
Next: Write a Python program to reverse a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics