Python:string.count()返回str在string里面出现的次数

最近代码中对字符串的操作比较多,因此送上一系列字符串操作窍门


python的string.count(str, begin=0, end=len(string)函数用于返回str在string中出现的次数

string为待检测的字符串,如:s='this is a new technology,and I want to learn this.'

参数1:str为待识别字符串,可以为串可以为字母但是要用引号包裹如str='this'或str='i'

参数2:begin表示string的起始位置,第一个位置是0,默认第一个位置为None

参数3:end表示string的终止位置,最后一个位置是string的长度,默认最后一个位置为None


示例代码:

s = 'this is a new technology,and I want to learn this.'
print(s.count('this', 0, len(s)))
输出为2


这里有一点要注意,区分大小写,如果

s = 'This is a new technology,and I want to learn this.'
那结果为1,因为This和this是两个不同的字符串


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值