扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-03-01 13:33:11
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

扫码添加客服微信