How can you count the characters (characters frequency) in a string without using if, while or for?
Asked
Active
Viewed 357 times
-1
-
`'aaabbc'.count('a')` gives `3` – Epsi95 Mar 06 '21 at 16:26
-
string = "abcdefa" string.count("a") – JACKDANIELS777 Mar 06 '21 at 16:27
-
At some level, there will be a need for/while to iterate the string. And an if statement to count a single character – OneCricketeer Mar 06 '21 at 16:28
-
iterate through all unique characters in string using `for char in set(your_string): print(your_string.count(char))` – Shijith Mar 06 '21 at 16:29
1 Answers
0
You can use Counter, it returns a dictionary with character as a key and its frequency as its value.
from collections import Counter
x = "abcdasbdd"
print(Counter(x))
Output
Counter({'d': 3, 'a': 2, 'b': 2, 'c': 1, 's': 1})

Cute Panda
- 1,468
- 1
- 6
- 11