您的位置:首页 > 编程语言 > Python开发

python中count()方法

2017-08-09 15:38 120 查看
Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。

count()方法语法:

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

返回子字符串在字符串中出现的次数

sub:搜索的子字符串

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

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

str = "this is string example....wow!!!"

sub = "i"
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow"  # 整体出现的次数
print "str.count(sub) : ", str.count(sub)
sub='my'
print "str.count(sub) : ", str.count(sub)
sub='sw'
print "str.count(sub) : ", str.count(sub)


运行结果:

str.count(sub, 4, 40) :  2
str.count(sub) :  1
str.count(sub) :  0
str.count(sub) :  0


当对象是一个嵌套的列表时,要查找嵌套列表中的列表参数count()方法同样可以完成

>>> ['a','iplaypython.com','c','b','a'].count('a')
2
>>> x = [1,2,'a',[1,2],[1,2]]
>>> x.count([1,2])
2
>>> x.count(1)
1
>>> x.count('a')
1
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: