0

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!

  • 1
    Based on an input of `awesome` what is the output you want? – Tim Biegeleisen Dec 30 '21 at 02:11
  • 1
    You can use [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) which is a `dict` subclass meaning that you can easily access count by using a key (which in case of a string will be the character). – Matiiss Dec 30 '21 at 02:13

3 Answers3

2

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


import collections

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

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

reference: https://docs.python.org/3/library/collections.html#collections.Counter

xxSirFartAlotxx
  • 394
  • 1
  • 11
0

Try list comprehension:

letters = ['e', 'm']
["Simple Example".count(letter) for letter in letters]
Joey Miths
  • 169
  • 5
  • there is a [slight issue regarding `count`](https://stackoverflow.com/a/2600208/14531062) tho I am not sure how it affects strings but I would guess that the effect is similar – Matiiss Dec 30 '21 at 02:16
  • @Matiiss It takes quite a few characters to count before this gets slower than Counter. – Kelly Bundy Dec 30 '21 at 02:17
-1

This should suffice the requirement.

a = {}
s = "awesome"
{a.update({i:s.count(i)}) for i in s if i not in a}
print(a)
Pranava
  • 15
  • 4