Dew*_*nks 1 python substring python-2.7
我需要计算子串'bob'出现在字符串中的nunber次数.
示例问题:查找字符串s中出现'bob'的次数
"s = xyzbobxyzbobxyzbob" #(here there are three occurrences)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
s = "xyzbobxyzbobxyzbob"
numBobs = 0
while(s.find('bob') >= 0)
numBobs = numBobs + 1
print numBobs
Run Code Online (Sandbox Code Playgroud)
由于Python中的find函数应该返回-1,如果子字符串未被发现,while循环应该在每次找到子字符串时打印出增加数量的bobs后结束.
然而,当我运行它时程序结果是无限循环.
对于这份工作,str.find效率不高.相反,str.count应该是你使用的:
>>> s = 'xyzbobxyzbobxyzbob'
>>> s.count('bob')
3
>>> s.count('xy')
3
>>> s.count('bobxyz')
2
>>>
Run Code Online (Sandbox Code Playgroud)
或者,如果要获得重叠事件,可以使用Regex:
>>> from re import findall
>>> s = 'bobobob'
>>> len(findall('(?=bob)', s))
3
>>> s = "bobob"
>>> len(findall('(?=bob)', s))
2
>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6059 次 |
| 最近记录: |