温馨提示×

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

小亿
87
2024-03-01 13:33:11
栏目: 编程语言

可以使用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

0