编写一个名为count_letters的函数,该函数将字符串作为参数并返回一个字典,该字典列出该字符串中每个字母的数量。该字符串可以包含字母以外的其他字符,但仅应计算字母。该字符串甚至可以是空字符串。字母的小写和大写版本应属于同一计数。字典的键应为大写字母。如果字母未出现在字符串中,则不会将其添加到字典中。例如,如果字符串为
"AaBb"
然后返回的字典应包含以下键值对:
{'A': 2,'B': 2}
def count_letters(string):
"""counts all the letters in a given string"""
your_dict = dict()
for x in string:
x = x.upper() # makes lowercase upper
if x not in your_dict:
your_dict[x]= 1
else:
your_dict[x] += 1
return your_dict
我上载时出现以下错误:
Test Failed: {'Q': 1,'U': 3,'I': 3,'S': 6,' ': 3,'C[48 chars]': 1} != {'S': 6,'T': 3,'O': 3,'C[32 chars]': 1}
+ {'C': 2,'D': 2,'E': 2,'P': 1,'Q': 1,'U': 3}
- {' ': 3,- '?': 1,- 'C': 2,- 'D': 2,- 'E': 2,- 'I': 3,- 'O': 3,- 'P': 1,- 'Q': 1,- 'S': 6,- 'T': 3,- 'U': 3}