Skip to main content

How to count the occurrences of a substring in a string in Python

How to count the occurrences of a substring in a string in Python.

Here's a detailed step-by-step tutorial on how to count the occurrences of a substring in a string using Python.

Step 1: Define the main string and the substring

First, you need to define the main string in which you want to count the occurrences of the substring. Let's say the main string is "Hello, how are you?".

main_string = "Hello, how are you?"

Next, define the substring that you want to count within the main string. Let's say the substring is "o".

substring = "o"

Step 2: Using the count() method

Python provides a built-in count() method that can be used to count the occurrences of a substring within a string. You can use this method to count the occurrences of the substring in the main string.

count = main_string.count(substring)
print("Number of occurrences:", count)

Output:

Number of occurrences: 3

In this example, the count() method returns the number of occurrences of the substring "o" in the main string "Hello, how are you?".

Step 3: Using a loop

If you want to count occurrences of a substring in a more complex string or if you want to perform additional operations for each occurrence, you can use a loop. Here's an example using a for loop:

count = 0
for i in range(len(main_string)):
if main_string[i:i+len(substring)] == substring:
count += 1
print("Number of occurrences:", count)

Output:

Number of occurrences: 3

In this example, the loop iterates over each character in the main string and checks if the substring matches a portion of the main string of the same length. If there is a match, the count is incremented.

Step 4: Using regular expressions

If you need more advanced pattern matching capabilities, you can use regular expressions. Python provides the re module for regular expression operations. Here's an example:

import re

count = len(re.findall(substring, main_string))
print("Number of occurrences:", count)

Output:

Number of occurrences: 3

In this example, the re.findall() function is used to find all occurrences of the substring in the main string. The len() function is then used to count the number of occurrences.

That's it! You now know how to count the occurrences of a substring in a string using Python. Feel free to experiment with different strings and substrings to explore the functionality further.