Search code examples
pythonlist-comprehensioncounteralphabeticalalphabetical-sort

Letter counting function


I need to define a function that takes a string and counts the number of letters of the alphabet(only lower case)in the input, for instance if I input "jack" it would return:

a=1,b=0,c=1,d=0,...,j=1,k=1,...,z=0.

So I implemented the following :

def l_count(str):
    str.lower()
    for ch in str:
        return str.count('a')

Which only returns the number of 'a' in the string. Since i don't want to do it for all the alphabet I thought about implementing a list comprehension like this :

al = [chr(i) for i in range(ord('a'),ord('z'))] 
def l_count(str):
    str.lower()
    for character in str:
        return str.count(al)

But I get an error :

must be str, not list 

I don't know how to change it since I get the same error.


Solution

  • Here's one way using collections.Counter:

    from collections import Counter
    from string import ascii_lowercase
    
    x = 'jack'
    
    c = Counter(dict.fromkeys(ascii_lowercase, 0))
    c.update(Counter(x))
    
    print(*(f'{k}={v}' for k, v in c.items()), sep=',')
    
    a=1,b=0,c=1,d=0,e=0,f=0,g=0,h=0,i=0,j=1,k=1,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0
    

    You may wish to add logic to lowercase your string, exclude punctuation, etc.