.count()
Published May 10, 2021Updated Mar 31, 2023
Contribute to Docs
The .count()
method finds the number of times the specified substring occurs within a given string. This method is case-sensitive.
Syntax
The .count()
method is called on a string using the following syntax:
string.count(substring, start=..., end=...)
substring
is the substring to search for.start
andend
are optional and specify the search’s starting and end positions.
Note: When not specified,
start
defaults to0
andend
defaults tolen(string)
, which means the search will be performed on the whole string.
Example
The following example uses .count()
to find the number of times li
appears in the string:
songTitle = "Supercalifragilisticexpialidocious"print(songTitle.count("li"))
The output is:
3
Codebyte Example
The codebyte example below is runnable and counts the number of times “at” is in the string starting at position 2
and ending at position 7
:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.