This post will discuss how to count occurrences of a character in a string in Python.

1. Using str.count() function

A simple and efficient solution is to get the total number of occurrences of a character in the string is using the str.count() function. This is the best solution to count a single character in a string.

Download  Run Code

2. Using collections.Counter class

If you need to find the frequency of several characters, calling the str.count() function for each character is not recommended. Instead, it would be best if you used the collections.Counter Python class. It works by storing each character as dictionary keys and their counts as dictionary values.

Download  Run Code

 
The Counter class takes linear time to preprocess the string and offers constant time count operations. However, it occupies some space to store the frequency of each character.

3. Using Dictionary

As an alternative to the collections.Counter class, you can also construct a simple dictionary. The idea is to store each character as dictionary keys and their counts as dictionary values.

Download  Run Code

4. Using Regular Expressions

You can also use regular expressions to count the total number of occurrences of a character in the string. However, we should best avoid regular expressions for this trivial task.

Download  Run Code

5. Using Lambda expressions

Finally, here’s a solution using lambda:

Download  Run Code

That’s all about counting occurrences of a character in a string in Python.