How to Count Occurrences in String in Python

Posted by Marta on December 18, 2020 Viewed 3080 times

In this tutorial I will share the main libraries and methods in python that allow you to count occurrences in a string and in a list.

Card image cap

In this tutorial I will share the main libraries and methods in python that allow you to count occurrences in a string and in a list. 

Python provides built-in modules and methods to solve this problem. The string type comes with the .count() method. Another option is using libraries. There are two built-in libraries to count frequency: re module(regular expressions), and the collections module. Let’s see each approach in detail.

Approach #1: Count Occurrences using .count()

One of the method of the string type in python is count(). This method returns the number of occurrences of a given character or word passed in as parameter.

count="Every next level of your life will demand a different you".count('e')
print(count)

Output:

8

The count(sub, start, end) method takes three parameters: sub is required, this is the substring that you are searching for. start is the index from which you start counting, this parameter is optional. And last, the end parameter which is the end index for the search. Let’s see some examples:

sentence = 'Hey there, How are you doing?'
print(sentence.count('Hey')
print(sentence.count('Hey',5)
print(sentence.count('How',0,7)

Output:

1
0
0

The code in line 3 will search the Hey substring from the index 5 to the end, in other word, in the substring here, How are you doing?.

In line 4, the code will search for the How substring in the substring Hey the, which the substring resulting from 'Hey there, How are you doing?'[0;7].

Approach #2: Count Occurrences using re module

Another approach is using the regular expression module available in python. The module is called re and provides regular expression matching operations. One of the operations provided is .findall().

import re
re.findall(pattern,string,flags=0)

This operation requires two mandatory parameters. The pattern to search, and the string to scan. The function will scanned left-to-right and returns the matches in the order found. Here is an example of how to use to count occurrences in a string.

import re
sentence = "Every next level of your life is the next challenge"
print(len(re.findall("e", sentence)))
print(len(re.findall("next", sentence)))

Output:

9
2

Approach #3: Count Occurrences using collection module

Another approach to count occurrences in python is using the Counter container from the module collections. The collection module is a built-in module, no need to install the module via pip. The collection module provides specialised containers for general purpose tasks. The counter is one of this containers. Instead of going through every character, place them in a map and count them, you can use the Counter class which already provides this functionality. See below and example of how to use it.

from collections import Counter
sentence = "Every next level of your life will demand a different you"
counter = Counter(sentence)
print(counter['a'])

Output:

2

Apart from counting, the Counter container also allows you to see the most common elements using the method .most_common(). See an example below:

c = Counter('abcdeabcdabcaba')
print(c.most_common(5))
print(c.most_common(2))

Output:

[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]
[('a', 5), ('b', 4)]

Count words occurrences in string

So far we have counted characters, What if you would like to count word occurrences? No problem, the previous three approaches will also work for counting words. You just need to replace the character by the word to count. See the example below:

sentence="Every next level of your life will demand a different you"
next_count = sentence.count('next') # a word in the sentence
the_count = sentence.count('the') # word that is not in the sentence
print(next_count)
print(the_count)

Output:

1
0

Count total characters in a string

We have seen how to count the occurrence of a word or a character. What if we would like to know the total number of characters in a string? The simplest way to achieve this is using the len method. See the example below that illustrates how to use the len() method.

total_characters = len('Every next level of your life will demand a different you')
print(total_characters)

Output:

57

What if you would like to know the number of different characters in a string? For example, if you have the following text ‘aaabbbbccc’, the number of different characters is 3, and the total character are 10.

The simplest way to do this is moving all the characters to a set. Since the set data structure doesn’t allow duplicates, it will save each character only once. Then counting the number of items in the set will return the number of different characters. See below how you can implement this in python:

sentence = 'Every next level of your life will demand a different you'
different_characters = set()
for ch in sentence:
    different_characters.add(ch)
print(len(different_characters))

Output:

18

Count occurrences in a list

We have seen how to count the number of occurrences in a string using the .count() method.As a result, you can also use this method to count occurrences in a list as follows:

list =['blue','red','green','blue','black','blue','red','green']
print(list.count('blue'))

Output:

3

Find last occurrence in string

Lastly another very commonly used operation when working with strings is finding last occurrence of some character in a string. In python you can do this using the .rfind() method. See how to use this function in the example below:

text = 'abcdeabcdabcaba'
print(text.rfind('a'))

Output:

14

Conclusion

To summarise, this tutorial covers the main three approaches that you can use to count the number of occurrences in a string or in a list. Thanks for reading this article and supporting this blog!

Happy coding!

Recommended articles

How to Get the day of the week in python

Learn How to Fix Valueerror: too many values to unpack

How to Fix Typeerror: int object is not subscriptable

See How to Convert XML to JSON in python

How to implement DFS to scan graph in python

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java