Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find occurrence to each character in given string
In this article, we will learn different methods to count the occurrence of each character in a given string. Python provides several approaches ranging from manual counting to built-in modules.
Problem statement ? We are given a string, we need to find the occurrence of each character in a given string.
Here we will be discussing 3 approaches as discussed below ?
Using Manual Dictionary Approach
This brute-force approach iterates through each character and manually counts occurrences using a dictionary ?
Example
test_str = "Tutorialspoint"
# count dictionary
count_dict = {}
for i in test_str:
# for existing characters in the dictionary
if i in count_dict:
count_dict[i] += 1
# for new characters to be added
else:
count_dict[i] = 1
print("Count of all characters in Tutorialspoint is :\n" + str(count_dict))
Output
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
Using collections.Counter()
The Counter class from the collections module provides a convenient way to count hashable objects ?
Example
from collections import Counter
test_str = "Tutorialspoint"
# using collections.Counter() we generate a dictionary
res = Counter(test_str)
print("Count of all characters in Tutorialspoint is :\n" + str(dict(res)))
Output
Count of all characters in Tutorialspoint is :
{'T': 1, 'u': 1, 't': 2, 'o': 2, 'r': 1, 'i': 2, 'a': 1, 'l': 1, 's': 1, 'p': 1, 'n': 1}
Using Dictionary Comprehension with set()
This approach uses dictionary comprehension with set() to get unique characters and count their occurrences ?
Example
test_str = "Tutorialspoint"
# using set() to calculate unique characters in the given string
res = {i : test_str.count(i) for i in set(test_str)}
print("Count of all characters in Tutorialspoint is :\n" + str(res))
Output
Count of all characters in Tutorialspoint is :
{'p': 1, 'a': 1, 'o': 2, 'n': 1, 'T': 1, 'l': 1, 's': 1, 'r': 1, 't': 2, 'u': 1, 'i': 2}
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Manual Dictionary | O(n) | Learning purposes |
| Counter() | O(n) | Most efficient and readable |
| Dictionary Comprehension | O(n²) | One-liner solutions |
Conclusion
Use collections.Counter() for the most efficient and readable solution. The manual dictionary approach helps understand the counting logic, while dictionary comprehension provides a concise one-liner.
