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")
For the letter count, the best way is to use the dictionary.
s = "string is an immutable object"
def letter_count(s):
d = {}
for i in s:
d[i] = d.get(i,0)+1
return d
Output:
{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r': 1, 'u': 1, 't': 3}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With