把字符串'aenabsascd'中的字符出现的次数统计出来,并以字典形式输出
方法一:
1 def count_str(str): 2 dic={} 3 for i in str: 4 dic[i]=str.count(i,0) 5 return dic 6 7 print(count_str('aenabsascd'))
结果:
{'a': 3, 'e': 1, 'n': 1, 'b': 1, 's': 2, 'c': 1, 'd': 1}
方法二:
1 def count_str(string): 2 dic = {} 3 for i in string: 4 dic[i] = dic.get(i, 0) + 1 5 return dic 6 7 print(count_str('aenabsascd'))
结果:
1 {'a': 3, 'e': 1, 'n': 1, 'b': 1, 's': 2, 'c': 1, 'd': 1}