Python .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=...)
substringis the substring to search for.startandendare optional and specify the search’s starting and end positions.
Note: When not specified,
startdefaults to0andenddefaults 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.
Learn Python on Codecademy
- Learn to analyze and visualize data using Python and statistics.
- Includes 8 Courses
- With Certificate
- Intermediate.13 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours