Search code examples
pythoncountletter

Count occurrence of all letters in string (python)


I have a given message:

message = """Nhpbz Qbspbz Jhlzhy dhz h Yvthu nlulyhs huk zahalzthu dov wshflk h jypapjhs yvsl pu aol lcluaz aoha slk av aol kltpzl vm aol Yvthu Ylwbispj huk aol ypzl vm aol Yvthu Ltwpyl.""" 

and i want to count the occurrences of all the letters (so from a to z). I know how to do it for one letter:

def count_letters(message, char):

    return sum(char == c for c in message)

print(count_letters(message, 'a'))

Is there a way to do it for all the letters without having to print every single one?


Solution

  • You can do it using collections.Counter():

    from collections import Counter
    str_count = Counter(message)
    print(str(str_count))
    

    Or if you want to use loops:

    str_count = {}
    
    for i in message:
        if i in str_count:
            str_count[i] += 1
        else:
            str_count[i] = 1
    
    print(str(str_count)
    

    More pythonic way:

    str_count = {i : message.count(i) for i in set(message)}
    
    print(str(str_count)