1

我需要计算子字符串'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 循环应该在每次找到子字符串时打印出递增的 bobs 数后结束。

但是,当我运行该程序时,它变成了一个无限循环。

4

6 回答 6

8

对于这个工作,str.find效率不是很高。相反,str.count应该是您使用的:

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

或者,如果您想获得重叠的出现,您可以使用 Regex:

>>> from re import findall
>>> s = 'bobobob'
>>> len(findall('(?=bob)', s))
3
>>> s = "bobob"
>>> len(findall('(?=bob)', s))
2
>>>
于 2013-11-07T22:55:42.470 回答
1

当您s.find('bob')从头开始搜索时,最终会一次又一次地找到同一个鲍勃,您需要将搜索位置更改为您找到的鲍勃的结尾。

string.find接受你可以传递的 start 参数来告诉它从哪里开始搜索,string.find还返回它找到 bob 的位置,所以你可以使用它,将 bob 的长度添加到它并将它传递给 next s.find

因此,在循环start=0开始时,如果您想从头开始搜索,则在循环内部如果find返回一个非负数,您应该将搜索字符串的长度添加到它以获得新的开始:

srch = 'bob'
start = numBobs = 0 while start >= 0:
    pos = s.find(srch, start)
    if pos < 0:
      break
    numBobs += 1
    start = pos + len(srch)

在这里我假设不考虑重叠的搜索字符串

于 2013-11-07T22:54:17.713 回答
0

find不记得上一场比赛在哪里并从那里开始,除非你告诉它。您需要跟踪匹配位置并传入可选start参数。如果你不这样做find只会bob一遍又一遍地找到第一个。

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.
于 2013-11-07T22:55:51.897 回答
0
def count_substring(string, sub_string):
count=a=0
while True:
    a=string.find(sub_string)
    string=string[a+1:]
    if a>=0:
        count=count+1;
    else:
        break
return count
于 2017-11-03T17:31:58.353 回答
0

在这里,您有一个简单的任务功能:

def countBob(s):
number=0
while s.find('Bob')>0:
    s=s.replace('Bob','',1)
    number=number+1        
return number

然后,您可以在需要时询问 countBob:

countBob('This Bob runs faster than the other Bob dude!')
于 2017-11-01T10:01:09.137 回答
0

这是一个在不使用正则表达式的情况下返回重叠子字符串数量的解决方案:(注意:这里的“while”循环是假设您正在寻找一个 3 个字符的子字符串,即“bob”)

bobs = 0
start = 0
end = 3
while end <= len(s) + 1 and start < len(s)-2 :
    if s.count('bob', start,end) == 1:
        bobs += 1
    start += 1
    end += 1

print(bobs)
于 2017-06-27T07:20:20.857 回答