Home > Enterprise >  How do I count the occurrences of multiple and different letters within a string?
How do I count the occurrences of multiple and different letters within a string?

Time:12-30

Example:

If I want to write code to determine how many occurrences of a particular character appear in a string, how would I do that for multiple characters? For example if I have these words, lets just say "Simple Example" and I want to find how many times the letter E exists inside these words, I would probably use something like:

example = "Simple Example".count("e")

But what if I wanted to find more letters than just e? Let's say I want to find the occurrences of the letters that exist within the word "awesome"?

Thanks in advance!

CodePudding user response:

Try list comprehension:

letters = ['e', 'm']
["Simple Example".count(letter) for letter in letters]

CodePudding user response:

Since you want to use counter, the best way perhaps would be:


import collections

a = "example"
counter = collections.Counter(a)

print(counter)
# Counter({'e': 2, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1})

print(counter.values())
# [2, 1, 1, 1, 1, 1]

print(counter.keys())
# ['e', 'x', 'a', 'm', 'p', 'l']

print(counter.most_common(3))
# [('e', 2), ('x', 1), ('a', 1)]

print(dict(counter))
# {'e': 2, 'x': 1, 'a': 1, 'm': 1, 'p': 1, 'l': 1}

  • Related