【问题标题】:How to count number of occurrences of a substring inside a string in Python?如何计算Python中字符串中子字符串的出现次数?
【发布时间】:2020-10-20 13:51:21
【问题描述】:

我正在尝试编写一个代码 sn-p,请求用户输入一个字符串 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

那么有人可以帮我修改此代码以提供所需的输出吗?提前致谢

【问题讨论】:

    标签: python string substring


    【解决方案1】:

    你可以使用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 所说,它使用了他所谓的滑动窗口方法

    我们获取子字符串的长度,并在每次迭代时检查它是否在字符串的那个“窗口”中:

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

    【讨论】:

    • 明白。谢谢 Ironkey。
    • 没问题,如果您喜欢某个特定的答案/解释,您可以单击绿色复选标记,以便以后有此问题的人接受,谢谢!
    【解决方案2】:

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

    示例:

    字符串:“呵呵呵呵”

    子字符串:“ehe”

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

    现在留下第一个字母“e”并将字母“he”与下一个字母“h”组合成“heh”是我们正在寻找的子字符串吗? - 没有

    现在留下第一个字母“h”并将字母“eh”与下一个字母“e”组合成“ehe”是我们正在寻找的子字符串吗?是的

    一直做到字符串的末尾并计算“是”的数量

    【讨论】:

    • 感谢老兄的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 2012-02-12
    • 2012-10-03
    • 2011-07-04
    • 2014-04-24
    相关资源
    最近更新 更多