Python string count() method
Python String count() Method
Description
The count() method returns the number of occurrences of the substring sub in the range [start, end]. The optional arguments start and end are interpreted the same way as in slice notation.
Syntax
The following is the syntax of the count() method: −
var.count(sub, start=0, end=len(string))
Parameters
- sub − The substring to search for.
- start − The index of the starting position for the search. The first character starts at index 0. By default, the search starts at index 0.
- end − The index of the ending position for the search. The first character starts at index 0. By default, the search ends at the last index.
Return Value
Returns the number of occurrences of a non-overlapping substring.
Example
var = "Explicit is better than implicit."
count1 = var.count('cit')
print("Original string:", var)
print("Count of 'cit':", count1)
count2 = var.count('i', 0, 10)
print("Count of 'i' in the first 10 characters:", count2)
When running this program, the following output is produced −
Original string: Explicit is better than implicit.
Count of 'cit': 2
Count of 'i' in the first 10 characters: 3