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:
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