string.count() is used to count the occurrences of a character or a substring in the given input string.
input_string = "how to do in java" substring = "a" print( input_string.count(substring) )
1. String count() Syntax
The syntax of
count() function is:
string.count(substring, start_index, end_index)
substring is required parameter. Start index and end index are optional parameters.
substring: whose occurrences needs to be counted in the given string.
start_index: from this index location, the search for the
end_index: in this index location, the search for the
1.2. Return Value
count() method returns the number of occurrences of
substring into the give
2. String count() Examples
Example 1: Counting the number of occurrences of a word in given sentence
In the given program, we are counting how many times “python” word appears in the string.
sentence = "python development is a lot easy with python supported IDEs" word = "python" print( sentence.count(word) )
Example 2: Counting the occurrences of a word within start and end index
In the given program, we are counting how many times “python” word appears in first 30 characters. The index location for first 30 characters – starts with 0 and ends at 29.
sentence = "Getting started with python is easy. python libs are so useful in AI and ML." word = "python" print( sentence.count(word, 0, 29) )
Happy Learning !!