首页 > 编程语言 > 详细

python中count函数的用法

时间:2020-05-09 11:49:23      阅读:56      评论:0      收藏:0      [点我收藏+]

描述

Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

count()方法语法:

str.count(sub, start= 0,end=len(string))

参数

sub -- 搜索的子字符串

start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。

end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。

返回值

该方法返回子字符串在字符串中出现的次数。

 

案例:

# 计算出以下字符串,每个字符出现的次数
a = "hello,world!"
print(a=,a)

#办法1
print ("统计a中各项的个数,办法1(字典):")
dicta = {}
for i in a:
    dicta[i] = a.count(i)
print (dicta)


# 办法2
print ("统计a中各项的个数,办法2(collections的counter):")
from collections import Counter
print(Counter(a))


# 办法3
print ("统计a中各项的个数,办法3(count方法):")
for i in a:
    print("%s:%d" %(i,a.count(i)))    #用count方法计算各项数量,简单打印出来而已

# 办法4(结果同3)
print ("统计a中各项的个数,办法4(列表count方法):")
lista = list(a)                           #字符串转为列表
print (lista:,lista)
for i in lista:
    print("%s:%d" %(i,lista.count(i)))    #用列表的count方法计算各项数量

打印结果:

a= hello,world!
统计a中各项的个数,办法1(字典):
{h: 1, e: 1, l: 3, o: 2, ,: 1, w: 1, r: 1, d: 1, !: 1}
统计a中各项的个数,办法2(collections的counter):
Counter({l: 3, o: 2, h: 1, e: 1, ,: 1, w: 1, r: 1, d: 1, !: 1})
统计a中各项的个数,办法3(count方法):
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1
统计a中各项的个数,办法4(列表count方法):
lista: [h, e, l, l, o, ,, w, o, r, l, d, !]
h:1
e:1
l:3
l:3
o:2
,:1
w:1
o:2
r:1
l:3
d:1
!:1

Process finished with exit code 0

 

python中count函数的用法

原文:https://www.cnblogs.com/wuzm/p/12855995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!