Python: Count occurrences of a substring in a string
Python String: Exercise-38 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-38.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics