Python program to find occurrence to each character in given string



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

 Live Demo

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

 Live Demo

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

 Live Demo

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.

Updated on: 2020-07-11T11:31:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements