w3resource

Python: Count occurrences of a substring in a string

Python String: Exercise-38 with Solution

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

Python String Exercises: 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:

Flowchart: Count occurrences of a substring in a string

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://198.211.115.131/python-exercises/string/python-data-type-string-exercise-38.php