Python: Count Occurrences of a Substring in a String

1. Introduction

Counting the number of times a specific substring appears in a larger string is a common text-processing task. While Python provides built-in methods for this, knowing how to do it from scratch can enhance one's understanding of string manipulation.

In this blog post, we will learn how to write a Python program to count occurrences of a substring in a string.

2. Program Overview

1. Create a function that iterates through the main string and checks for occurrences of the substring.

2. Accept the main string and the target substring from the user.

3. Call the function to count the occurrences.

4. Display the result to the user.

3. Code Program

# Python program to count occurrences of a substring in a string

def count_substring(main_str, sub_str):
    """Function to count occurrences of a substring."""
    count = 0  # Initialize the count
    index = 0  # Start from the beginning of the string
    while index < len(main_str):
        position = main_str.find(sub_str, index)
        if position == -1:
            return count  # No more occurrences found
        count += 1
        index = position + 1  # Move past the last found substring
    return count

# Accept input from the user
string_input = input("Enter the main string: ")
substring_input = input("Enter the substring to search for: ")

# Calculate the occurrences
occurrences = count_substring(string_input, substring_input)

# Display the result
print(f"The substring '{substring_input}' appears {occurrences} times in the string '{string_input}'.")


Enter the main string: java guides java examples
Enter the substring to search for: java
The substring 'java' appears 2 times in the string 'java guides java examples'.

4. Step By Step Explanation

1. The function count_substring is defined to count the occurrences of the sub_str inside main_str.

2. A while loop runs until the end of the main string. Within the loop, we use the find method of the string which returns the starting position of the first occurrence of the substring. If no more occurrences are found, it returns -1.

3. Every time the substring is found, we increment our count.

4. To avoid counting the same occurrence multiple times, we set index to the position after the last found occurrence. This way, the search continues from the next character onwards.

5. Outside the function, we get the main string and target substring from the user.

6. The function is then called with these values, and the result is displayed.

7. The provided output section showcases the output for a sample input where the main string is "hello hello world" and the substring is "hello".