Return the count of a given substring from a string

Here’s an example Python code to return the count of a given substring from a string:

# Define a function to count the number of occurrences of a substring in a string
def count_substring(string, substring):
    count = 0
    index = 0
    while True:
        index = string.find(substring, index)
        if index == -1:
            break
        count += 1
        index += len(substring)
    return count

# Test the function with a sample string and substring
string = "Hello, World! How are you today? World is beautiful."
substring = "World"
count = count_substring(string, substring)
print("The count of substring '{}' in string '{}' is {}.".format(substring, string, count))

In this code, we define a function count_substring() that takes two arguments: string and substring. This function uses the find() method to search for the first occurrence of the substring in the string. If it finds a match, it increments the count variable and continues searching for the next occurrence of the substring starting from the index immediately after the last match. This process continues until the substring is no longer found in the string. Finally, the function returns the count of the substring.

In the main program, we test the count_substring() function by calling it with a sample string and substring. We then use the print() function to output the count of the substring in the string.

When you run this code, it should output:

The count of substring 'World' in string 'Hello, World! How are you today? World is beautiful.' is 2.

Note that you can replace the sample string and substring with any other values you want to test the function with.

Related Examples

1. Python Program to Print Hello world!

2. Calculate the multiplication and sum of two numbers

3. Python Program to Find the Square Root

4. Python Program to Calculate the Area of a Triangle

5. Python Program to Solve Quadratic Equation

6. Python Program to Swap Two Variables

7. Python Program to Generate a Random Number

8. Print the following pattern

9. Python Program to check if the given number is a palindrome number

10. Python Program to print multiplication table form 1 to 10

11. Print downward Half-Pyramid Pattern with Star (asterisk)

12. Python Program to Convert Kilometers to Miles

13. Python Program to Check if a Number is Positive, Negative or 0

14. Python Program to Find the Sum of Natural Numbers

15. Print the sum of the current number and the previous number in Python

Leave a Reply

Your email address will not be published. Required fields are marked *

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial