-2

How can you count the characters (characters frequency) in a string without using if, while or for?

4
  • 'aaabbc'.count('a') gives 3 Commented Mar 6, 2021 at 16:26
  • string = "abcdefa" string.count("a") Commented Mar 6, 2021 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 Commented Mar 6, 2021 at 16:28
  • iterate through all unique characters in string using for char in set(your_string): print(your_string.count(char)) Commented Mar 6, 2021 at 16:29

1 Answer 1

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})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.