
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Occurrence of Each Character in Given String using Python
In this article, we will learn about the solution to the problem statement given below.
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:L
Approach 1 − The brute-force approach
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}
Approach 2 − Using the collections module
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}
Approach 3 − Using set() in a lambda expression
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(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}
Conclusion
In this article, we have learned about how we can find the occurrence of each character in a given string.
Advertisements