Count occurrences of a character in a Python string
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.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABADACB" n = s.count('A') print(n) # 3 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
import collections if __name__ == '__main__': s = "ABADACB" counter = collections.Counter(s) n = counter['A'] print(n) # 3 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
if __name__ == '__main__': s = "ABADACB" chars = dict.fromkeys(s, 0) for c in s: chars[c] += 1 n = chars['A'] print(n) # 3 |
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.
|
1 2 3 4 5 6 7 8 9 |
import re if __name__ == '__main__': s = "ABADACB" n = len(re.findall('A', s)) print(n) # 3 |
5. Using Lambda expressions
Finally, here’s a solution using lambda:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = "ABADACB" n = sum(map(lambda x: 1 if x == 'A' else 0, s)) print(n) # 3 |
That’s all about counting occurrences of a character in a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)