Linux 拨号vps windows公众号手机端

python怎么统计字符串字符出现次数

lewis 8年前 (2017-01-12) 阅读数 8 #程序编程
文章标签 python

可以使用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
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

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

热门