Python String count() Method

Counts occurrences of a substring

Usage

The count() method returns the number of times the substring sub appears in the string.

You can limit the search by specifying optional arguments start and end.

Syntax

string.count(sub,start,end)

Python string count() method parameters
ParameterConditionDescription
subRequiredAny string you want to search for
startOptionalAn index specifying where to start the search.
Default is 0.
endOptionalAn index specifying where to stop the search.
Default is the end of the string.

Basic Example

Example: Count occurrences of ‘Big’ in the string

S = 'Big, Bigger, Biggest'
x = S.count('Big')
print(x)	# 3

Limit count() Search to Substring

If you want to search the string from the middle, specify the start parameter.

Example: Count occurrences of ‘Big’ from 5th character

S = 'Big, Bigger, Biggest'
x = S.count('Big',5)
print(x)	# 2

You can specify where to stop the count() search with end parameter.

Example: Count occurrences of ‘Big’ between 5th to 13th character

S = 'Big, Bigger, Biggest'
x = S.count('Big',5,13)
print(x)	# 1

Optional arguments start and end are interpreted as in slice notation.

Meaning, S.count('Big',5,13) is similar to S[5:13].count('Big')