count在python中怎么定义_python中count函数的用法

描述

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 ina:

dicta[i]=a.count(i)

print (dicta)

# 办法2

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

print(Counter(a))

# 办法3

print ("统计a中各项的个数,办法3(count方法):")for i ina:

print("%s:%d" %(i,a.count(i))) #用count方法计算各项数量,简单打印出来而已

# 办法4(结果同3)

print ("统计a中各项的个数,办法4(列表count方法):")

lista=list(a) #字符串转为列表

print ('lista:',lista)for i inlista:

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:1e:1l:3l:3o:2,:1w:1o:2r:1l:3d:1

!:1统计a中各项的个数,办法4(列表count方法):

lista: ['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd', '!']

h:1e:1l:3l:3o:2,:1w:1o:2r:1l:3d:1

!:1Process finished with exit code0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值