Python count()方法:统计字符串出现的次数
count 方法用于检索指定字符串在另一字符串中出现的次数,如果检索的字符串不存在,则返回 0,否则返回出现的次数。
count 方法的语法格式如下:
<pre class="brush:html;toolbar:false">str.count(sub[,start[,end]])</pre>此方法中,各参数的具体含义如下:
str:表示原字符串;
sub:表示要检索的字符串;
start:指定检索的起始位置,也就是从什么位置开始检测。如果不指定,默认从头开始检索;
end:指定检索的终止位置,如果不指定,则表示一直检索到结尾。
【例 1】检索字符串“c.biancheng.net”中“.”出现的次数。
<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.count('.') 2</pre>【例 2】
<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.count('.',1) 2 >>> str.count('.',2) 1</pre><span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);">我们已经学过,字符串中各字符对应的检索值,从 0 开始,因此,本例中检索值 1 对应的是第 2 个字符‘.’,从输出结果可以分析出,从指定索引位置开始检索,其中也包含此索引位置。</span>
<span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);">【例 3】</span>
<pre class="brush:html;toolbar:false">>>> str = "c.biancheng.net" >>> str.count('.',2,-3) 1 >>> str.count('.',2,-4) 0</pre><span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);"></span>
<span style="color: rgb(68, 68, 68); font-family: "Helvetica Neue", 微软雅黑, "Microsoft Yahei", Helvetica, Arial, sans-serif; white-space: normal; background-color: rgb(255, 255, 255);">
</span>
您可能感兴趣的文章:
python count返回什么
python怎么统计列表中元素的个数
python统计不同字符的个数
Python count()方法:统计字符串出现的次数
一文搞定统计字符串中某字符出现的频次
Python字符串操作常用知识点(3)
python string是什么
python rsplit是什么属性
php 统计字数(支持中英文)的实现代码
php截取字符串长度函数详解