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.



Follow us on Facebook and Twitter for latest update.