python怎么统计字符串字符出现次数
lewis
2017-01-12
16次阅读
可以使用collections库中的Counter类来统计字符串中字符的出现次数。示例如下:
from collections import Counter
s = "hello world"
counts = Counter(s)
for char, count in counts.items():
print(f"{char}: {count}")
运行以上代码,输出结果为:
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1

发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。