python – How many times different letters appear in different words? – Education Career Blog

How to know how many times strings s , t and n appear in each of the following words to have an output like this:

  • descriptions: s 2 , t 1 , n 1
  • statements s 2 , t 3 , n 1

The words are not known in advance.The first thing came to my mind was to make a dictionary, but for dictionaries we can only have two unknowns, so any hints how to approach it?
Thanks in advance.


In Python ≥2.7 and ≥3.1 you could use collections.Counter.

>>> from collections import Counter
>>> Counter("descriptions")
Counter({'i': 2, 's': 2, 'c': 1, 'e': 1, 'd': 1, 'o': 1, 'n': 1, 'p': 1, 'r': 1, 't': 1})

(For Python ≥2.5 there is an implementation in

The Counter class has the usual dictionary interface, so you could use x'n' to get the count.

>>> print("%s %s, %s %s, %s %s" % ('s', _'s', 't', _'t', 'n', _'n'))
s 2, t 1, n 1


from collections import defaultdict
def counter(STRING):
  for i in STRING:
    if i in "stn":
  return h
for s in 'description','statements':
    print k + " for " + s


Naive implementation:

d = {}
for c in s:
  dc = s.count(c)

Leave a Comment