My homework problem is to write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts. However, my code includes white space and commas as a part of the dictionary which i don’t want. Can you please help me out. How do i remove the white space from my list? Here is my code?
import string def LetterCount(str): str= str.lower().strip() str = str.strip(string.punctuation) list1=list(str) lcDict= {} for l in list1: if l in lcDict: lcDict[l] +=1 else: lcDict[l]= 1 print lcDict LetterCount("Abracadabra, Monsignor")
Advertisement
Answer
You can also check if l is an alphabetic character (if l.isalpha()
)
Example:
import string def LetterCount(str): str= str.lower().strip() str = str.strip(string.punctuation) list1=list(str) lcDict= {} for l in list1: if l.isalpha(): if l in lcDict: lcDict[l] +=1 else: lcDict[l]= 1 print lcDict LetterCount("Abracadabra, Monsignor")