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

The python string count function is used to get the number of occurrences of a substring in the given string. The means count() method will search the substring in the given string and returns how many times the substring is had it.

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

Syntax

string.count(value, start, end)

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

An 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 the whole string.

txt = "Python is programing language. Python is easy. Learn Free Python "

x = txt.count("Python")

print(x)

Output: 3

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

Search from position 0 to 18:

txt = "Python is programing language. Python is easy. Learn Free Python "

x = txt.count("Python", 0, 18)

print(x)

Output: 1

Python count string length

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

str = "Hello Python"
print(len(str))

Output: 12

Read more examples:– Python length of a list

Q: How to count total characters in string python?

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

str1 = "Hello"
 
x = len(str1)
 
print(x)

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.

def frequencyCount(string, substr):
    count = 0
    pos = 0
    while (True):
        pos = string.find(substr, pos)
        if pos > -1:
            count = count + 1
            pos += 1
        else:
            break
    return count


print("The count is: ", frequencyCount("thatthathat", "that"))

Output: 2

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

Note:
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.