Count number of occurrences or substrings of a character in a string in python; This tutorial will demonstrate these things by writing a program to count the number of times occurrences character appears in a given string in python. And you will learn how to count occurrences of a character or substring in a string with examples.
How to count the number of occurrences of characters in a string in python
Use the python standard built-in string count() function to count a number of occurrences or substrings of a character in a string in python.
Before writing a Python program to count occurrences of a substring in a string, you must know about the python count() function:
Python String Count Function
Python string count() is a standard inbuilt function, which is used to find number of occurrences of the substring in the given string. The count() method searches the substring in the given string and returns how many times the substring is present in it.
It also takes optional parameters to start and end to specify the starting and ending positions in the string respectively.
Syntax of the python count functions is the following:
string.count(substring, start, end)
Here, the python count function accept three parameters and two parameters are optional.
substring is the first parameter of the python count function and is required parameter which is a string whose count is to be found.
The start parameter is an Optional which is the starting index within the string where the search starts.
The end parameter is an Optional which is the ending index within the string where the search ends.
Example 1: python count number of occurrences in the string
str = 'welcome to python words. Learn online python free.' substring = 'on' count = str.count(substring) print('The substring occurs {} times'.format(count))
In the above python program to count the number of characters in a string. i.e. on as a substring and check how many times it is repeated inside the Python String.
You can see the output of above python program to count the number of characters in a string:
The substring occurs 3 times
Example 2: python count function with start and end
str = 'welcome to python words. Learn online python free.' substring = 'on' count = str.count(substring, 10, 20) print('The substring occurs {} times'.format(count))
The above python program to count substring in the given string, we have used start and end parameters of python count function. It will count the number of substrings between the 10th and 20th index characters. In our example, on occurs only one time between those characters that is why we see the one time.
In the above python program to count the number of characters in a string. i.e. on as a substring and check how many times it is repeated inside the Python String.
You can see the output of the above python program to count the number of characters in a string:
The substring occurs 1 times