如何计算Python中字符串中子字符串的出现次数?

How to count number of occurrences of a substring inside a string in Python?

我正在尝试编写一个代码片段,请求用户输入一个字符串 s,然后是一个子字符串 ss。然后程序必须计算 sss 中出现的次数。例如,如果用户输入 s = ‘azcbobobegghakl’ss = ‘bob’,那么程序应该打印:Number bob 出现的次数是:2.

到目前为止,这是我的代码:

def count(s,ss):
    Occurrence = 0
    if ss in s :
        for ss in s :
            Occurrence += 1
    return Occurrence 

#Main program : 
    
s = str(input("Choose a string: "))
    
ss = str(input("Choose a substring:")) 
    
print ("Number of times " + str(ss) + " occurs is : " + str(count(s,ss)) ) 

我想要的输出是这样的:

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2

但我却得到了这个:

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8

所以有人可以帮我修改这段代码来实现期望的输出吗?提前致谢

你可以使用count

print("hellohel".count("hel"))
2

如果您想计算重叠次数...也许这会有所帮助

def countOverlapping(string, item):
    count = 0
    for i in range(0,len(string)):
        if item in string[i:len(item)+i]:
            count += 1
    return count

print(countOverlapping("ehehe", "ehe"))

输出应该是...

2

这是如何运作的?

正如@SomeDude 提到的那样,它使用了他所谓的滑动 window 方法

我们获取子字符串的长度并检查它是否在每次迭代的字符串的“window”中:

is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1

您需要采用滑动 window 方法来获取字符串中子字符串的数量。

示例:

字符串:“呵呵呵呵”

子字符串:“ehe”

从前 3 个(因为子字符串的长度为 3)字母“ehe”开始-它是我们要查找的子字符串吗? - 是的。

现在留下第一个字母“e”,将字母“he”与下一个字母“h”组合形成“heh”,这就是我们要找的子串吗? - 没有

现在保留第一个字母“h”,将字母“eh”与下一个字母“e”组合形成“ehe”,这就是我们要查找的子字符串吗?是的

执行到字符串末尾并计算“是”的数量