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

# Count occurrences of 'Big' in the string
S = 'Big, Bigger, Biggest'
x = S.count('Big')
print(x)
# Prints 3

Limit count() Search to Substring

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

# Count occurrences of 'Big' from 5th character
S = 'Big, Bigger, Biggest'
x = S.count('Big',5)
print(x)
# Prints 2

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

# Count occurrences of 'Big' between 5th to 13th character
S = 'Big, Bigger, Biggest'
x = S.count('Big',5,13)
print(x)
# Prints 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')