查找子字符串在给定字符串中出现的次数

Finding how many times a substring appears in a given string

s = 'This is a bad bad example'
sub = 'bad'

start = 0
count = 0
while True:
    start = s.find(sub,start) + 1
    if start >= 0:
        count = count+1
    else:
        break

print 'The number of times bad appears in the given string is: ' + str(count)

这是我试过的。我试图自己调试它,但我无法弄清楚我哪里出错了。我是否错误地使用了 find() 函数?

应该不会太难,最好的部分是 python 无需循环遍历所有内容!

试试这个:

>>> a = "this is a bad bad example"
>>> a.count('bad')
2

a.count(b) returns b 在字符串或列表 a.

中出现的次数

编辑 要解决您的代码:

while True:
    start = s.find(sub,start) + 1
    if start >= 0:
        count = count+1
    else:
        break

您使用的 find() 是正确的,但是当找不到更多 bad 时,它将 return -1,然后您将其添加到 (也正确,由于 0 索引)但是你然后检查 start >= 0 这将总是 return true 因为 -1(错误结果)将变为 0(肯定结果)

试试这个:

start = -1 # start at -1 now, you'll see why...
while True:
    start = s.find(sub,start + 1)
    if start >= 0:
        count = count+1
    else:
        break

因此,您考虑了 find() 调用中的差一错误,而不是将其存储在终止条件中。更好的是:

while start >= 0:
    start = s.find(sub,start+1)
    count += 1

我可能是错的,但我认为如果子字符串 "overlap",计数不会像您预期的那样工作。例如:

s1="dadad"
s2='dadsdad'

sub="dad"

s1.count(sub) #1
s2.count(sub) #2

我是这样解决的:

def overlapping_substring_count(string,sub_string):
    l=len(sub_string)
    count=0
    for i in range(len(string)-len(sub_string)+1):
        if(string[i:i+len(sub_string)] == sub_string ):      
            count+=1
    return count  

s1='dadad'
s2="dad"

print(overlapping_substring_count(s1,s2))