Count occurrences of each character in a String in Python

avatar

Borislav Hadzhiev

Last updated: Sep 21, 2022

banner

Photo from Unsplash

Count occurrences of each character in a String in Python #

Use the collections.Counter class to count the occurrences of each character in a string, e.g. my_dict = Counter(my_str.lower()). The Counter class will return a dictionary-like object with the string's characters as keys and the number of occurrences as values.

main.py
from collections import Counter my_str = 'Bobby' # ✅ count occurrences of each character in string (collections.Counter) my_dict = Counter(my_str.lower()) print(my_dict) # 👉️ Counter({'b': 3, 'o': 1, 'y': 1}) print(my_dict['b']) # 👉️ 3 print(my_dict['o']) # 👉️ 1 # ------------------------------------------ # ✅ count occurrences of each character in string (for loop) my_dict = {} for char in my_str: if char.lower() in my_dict: my_dict[char.lower()] += 1 else: my_dict[char.lower()] = 1 print(my_dict) # 👉️ {'b': 3, 'o': 1, 'y': 1}

The first example uses the collections.Counter class to count the occurrences of each character in a string.

The Counter class is a subclass of dict and is used for counting items.

main.py
from collections import Counter my_str = 'Bobby' my_dict = Counter(my_str.lower()) print(my_dict) # 👉️ Counter({'b': 3, 'o': 1, 'y': 1}) print(my_dict['b']) # 👉️ 3 print(my_dict['o']) # 👉️ 1
The class stores the characters of the string as keys and their counts as values.

Notice that we used the str.lower() method to convert the string to lowercase when passing it to the Counter() class.

If you want to distinguish between uppercase and lowercase letters, remove the call to the str.lower() method.

main.py
from collections import Counter my_str = 'Bobby' my_dict = Counter(my_str) print(my_dict) # 👉️ Counter({'b': 2, 'B': 1, 'o': 1, 'y': 1}) print(my_dict['b']) # 👉️ 3 print(my_dict['o']) # 👉️ 1

Alternatively, you can use a for loop.

Count occurrences of each character in a String using a for loop #

To count the occurrences of each character in a string:

  1. Declare a new variable that store an empty dictionary.
  2. Use a for loop to iterate over the string.
  3. Increment the count for each character or initialize it to 1.
main.py
my_str = 'Bobby' my_dict = {} for char in my_str: if char.lower() in my_dict: my_dict[char.lower()] += 1 else: my_dict[char.lower()] = 1 print(my_dict) # 👉️ {'b': 3, 'o': 1, 'y': 1}

We used a for loop to iterate over the string.

On each iteration, we check if the current character is present in the dictionary.

When used with a dictionary, the in operator checks for the existence of the specified key in the dict object.

If the character is present in the dictionary, we increment its value, otherwise we initialize the character to 1.

If you want to distinguish between uppercase and lowercase letters, remove the calls to the str.lower() method.

main.py
my_str = 'Bobby' my_dict = {} for char in my_str: if char in my_dict: my_dict[char] += 1 else: my_dict[char] = 1 print(my_dict) # 👉️ {'B': 1, 'o': 1, 'b': 2, 'y': 1}

Dictionaries in Python 3.7 and more recent versions preserve the insertion order of keys, so the result is quite readable.

Which approach you pick is a matter of personal preference. I'd go with the for loop because it's quite easy to read and intuitive.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.