python中count()方法,统计字符串字符或子串

count()方法描述

count()方法,是python内置的字符串方法之一,可以用来统计python字符串对象中指定的字符或子串在该对象中出现的次数。一般情况下,count()可以接受一个或两个或三个参数。


count()方法参数及用法

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

第一个参数sub用来指定count()方法所要统计的字符或子串;第二个参数start指定count()方法统计的起始的索引位置,默认为0;第三个参数end指定count()方法统计的终止索引位置,默认为字符串的长度len(string);


count()方法返回值

一般情况下为int类型的值,表示的是字符或子串在原字符串中出现的次数;

count()方法实例代码

>>> str = '笨鸟工具,x1y1z1.com'
>>> str.count('1')
3
>>> a = str.count('1')
>>> type(a)
<class 'int'>
>>> str.count('中')
0
>>> str.count('1',0,6)
0
>>> str.count('1',6)
3

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.