Skip to main content
 首页 » 编程设计

python之字符串中某个子串出现的次数

2025年05月04日27cmt

我需要计算子字符串 'bob' 在字符串中出现的次数。

示例问题:找出 'bob' 在字符串 s 中出现的次数

"s = xyzbobxyzbobxyzbob"  #(here there are three occurrences) 

这是我的代码:

s = "xyzbobxyzbobxyzbob" 
 
numBobs = 0 
 
while(s.find('bob') >= 0) 
   numBobs = numBobs + 1 
   print numBobs 

由于 Python 中的 find 函数应该在未找到子字符串时返回 -1,因此 while 循环应该在每次找到子字符串时打印出递增的 bob 数后结束。

然而,当我运行它时,程序变成了一个无限循环。

请您参考如下方法:

对于这项工作,str.find 不是很有效。相反,str.count应该是你使用的:

>>> s = 'xyzbobxyzbobxyzbob' 
>>> s.count('bob') 
3 
>>> s.count('xy') 
3 
>>> s.count('bobxyz') 
2 
>>> 

或者,如果您想要重叠出现,您可以使用正则表达式:

>>> from re import findall 
>>> s = 'bobobob' 
>>> len(findall('(?=bob)', s)) 
3 
>>> s = "bobob" 
>>> len(findall('(?=bob)', s)) 
2 
>>>