def charcount(stri):
for i in stri:
count = 0
for j in stri:
if stri[i] == stri[j]:
count += 1
我是 python 的新手,目前正在学习字符串操作,谁能告诉我这个程序有什么问题吗?该函数尝试打印给定字符串中每个字符的计数。
例如:string ="你身后有影子" 我想计算每个字符在字符串中出现了多少次
请您参考如下方法:
可以使用 Counter() 计算字符串中的字符数类如:
代码:
from collections import Counter
def charcount(stri):
return Counter(stri)
print(charcount('The function try to print count of each character '
'in given string . Please help'))
结果:
Counter({' ': 14, 'e': 7, 'n': 7, 't': 7, 'c': 5, 'i': 5,
'r': 5, 'h': 4, 'o': 4, 'a': 4, 'f': 2, 'u': 2,
'p': 2, 'g': 2, 's': 2, 'l': 2, 'T': 1, 'y': 1,
'v': 1, '.': 1, 'P': 1})
