Posted by Marta on December 18, 2020 Viewed 8423 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.
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.
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)
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)
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].
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
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)))
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'])
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))
[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)] [('a', 5), ('b', 4)]
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)
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
total_characters = len('Every next level of your life will demand a different you') print(total_characters)
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))
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'))
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'))
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!
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
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