Python string count function | Count total characters in string & occurrences

Python string count function is used to get a number of occurrences of a substring in the given string. Means count() method will search the substring in the given string and returns how many times the substring is have it.

Note: count() function is case sensitive, means if you find caps lock word then it will count only same.


Parameter Values

  • value(substring):– string whose count is to be found.
  • start:- The position to start the search. Default is 0 (Optional)
  • end:– The position to end the search. Default is the end of the string

Return Value:

The number of occurrences of the substring in the given string.

String count function example in Python

A example of count number of occurrences in string in python. We are not using a start and end limit for this example.

Note: Index in Python starts from 0, not 1.

Search “Python” in whole string.

Output: 3

Count word occurrences in string substring using start and end in python

Search from position 0 to 18:

Output: 1

Python count string length

Use len() function to get the length of string. See below example:-

Output: 12

Read more examples:– Python length of list

Q: How to count total characters in string python?

Answer: To get total characters in the string you have to use string len() function.

Output: 5

Q: Count overlapping substrings python.

Answer: Count() function does not count the overlapping strings. For this, we need to write our own function definition.

Keep a count variable to store the count and pos to track the starting index of the sub-string. When the sub-string is encountered, increment the counter and check from the next index.

This is how we calculate the overlapping substrings.

Output: 2

Do comment if you have any doubts and suggestions on this tutorial.

IDE: PyCharm 2020.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples string.count python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.