
In the example below, let’s see how we can see how often the letters a and e occur: > print(collection) What this means is that we can access the occurrences of different items in our object by passing in a dictionary accessor. What’s great about this class is that it contains a dictionary-like element that contains occurrences of every iterable item in the item that was passed in. We can confirm this by running print(type(collection)) which returns. What you can see is that what’s returned is a Counter object. Finally, we printed the new collection object.We passed the string into a Counter object and called it collection.We then assigned our string to the variable a_string.We imported Counter from the collections module.
Python count occurrences in list stack code#
What we’ve accomplished in the code above is the following: from collections import CounterĪ_string = 'the quick brown fox jumps over the lazy dog'

In this case, our collection will be a string: 'the quick brown fox jumps over the lazy dog'. The module provides a number of help classes to work with, well, collections of different items. In order to find a more flexible and efficient way to count occurrences of a character in a Python string, you can also use the Counter object from the built-in collections module. Count Number of Occurrences in a Python String with Counter count() method to count the number of times both a single character and a string appeared in a larger string. In the example above you used the built-in string. > print('the appears this many times: ', a_unt('the')) > print('o appears this many times: ', a_unt('o')) In the example below, we’ll load a sample string and then count the number of times both just a character and a substring appear: > a_string = 'the quick brown fox jumps over the lazy dog' The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string.
