繁体   English   中英

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

[英]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)返回b在字符串或列表a中出现的次数。

编辑要解决您的代码:

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

您正确使用了find() ,但是当没有更多bad s时,它将返回-1 ,然后将其添加到1(同样由于0索引而正确),但是请检查start >= 0将始终返回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

我可能是错的,但是如果子字符串“重叠”,我认为count不能像您期望的那样工作。 例如:

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM