Python String count() Method

Counts occurrences of a substring


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.



Python string count() method parameters
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')
# 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)
# 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)
# 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')