Python字符串count()
方法返回[start,end]
范围内子字符串sub
的出现次数。可选参数start
和end
被解释为切片符号。
语法
以下是count()
方法的语法 -
str.count(sub, start = 0,end = len(string))
参数
- sub - 这是要搜索的子字符串。
- start - 从此索引开始搜索。第一个字符索引是
0
。默认情况下,从0
索引开始搜索。 - end - 从此索引结束搜索。第一个字符索引是
0
。 默认情况下,搜索结束于最后一个索引。
返回值
- 此方法返回
[start,end]
范围内子字符串sub
的出现次数。
示例
以下示例显示了count()
方法的用法。
#!/usr/bin/python3
str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
当运行上面的程序,它产生以下结果 -
str.count('i') : 3
str.count('exam', 4, 40) : 1