统计字符串里每个字符的个数
方法一:
str = "hello world"
from collections import Counter
print(Counter(str))方法二:
str = "hello world"
new_list=[]
# 字符串变列表
mylist = str.split()
# 列表变字符串
mystr = "".join(mylist)
print(type(mystr))
for i in mystr:
if i not in new_list:
# 把字符串里的元素放在列表里
new_list.append(i)
print("字符%s在字符串中出现的次数为%d"%(i,mystr.count(i)))方法三:
str = "hello world"
my_set = set(str)
for i in my_set :
if i.isalpha():
print("字母%s出现的次数为 %d"%(i,str.count(i)))
本文介绍了三种统计字符串中字符出现次数的方法:使用Python标准库Counter快速实现;将字符串转换为列表并统计各元素数量;利用集合筛选字母字符并计算频次。
1万+





