[英]How to count number of occurrences of a substring inside a string in Python?
I am attempting to write a code snippet that requests from the user to enter a string s
and then a substring ss
.我正在尝试编写一个代码片段,请求用户输入字符串
s
然后输入子字符串ss
。 The program will then have to count the number of occurrences of ss
in s
.然后程序必须计算
s
中ss
出现的次数。 For example if the user enters s = 'azcbobobegghakl'
and ss = 'bob'
, then the program should print: Number of times bob occurs is: 2.例如,如果用户输入
s = 'azcbobobegghakl'
和ss = 'bob'
,则程序应打印:鲍勃发生的次数为:2。
Here is my code so far :到目前为止,这是我的代码:
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)) )
My desired output would be this:我想要的输出是这样的:
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2
But instead I get this :但是我得到了这个:
Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8
So can someone please help me modify this code to deliver the desire output?那么有人可以帮我修改此代码以提供所需的输出吗? Thanks in advance
提前致谢
you can use count
你可以使用
count
print("hellohel".count("hel"))
2
If you want to count overlapping occurrences... maybe this can help如果您想计算重叠的出现次数...也许这会有所帮助
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"))
output should be...输出应该是...
2
How does that work?这是如何运作的?
as @SomeDude mentioned it uses what he calls a sliding window approach正如@SomeDude 提到的,它使用了他所谓的滑动窗口方法
we take the length of the substring and check if its in that "window" of the string each iteration:我们取子字符串的长度并检查它是否在每次迭代的字符串“窗口”中:
is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1
You need to go for a sliding window approach to get count of substrings in a string.您需要采用滑动窗口方法来获取字符串中子字符串的计数。
example:例子:
string : "ehehehe"字符串:“呵呵”
substring : "ehe"子字符串:“嗯”
start with first 3 ( because length of substring is 3 ) letters "ehe"- is it the substring we are looking for?从前 3 个(因为子串的长度是 3 个)字母“ehe”开始——它是我们要找的子串吗? - yes.
- 是的。
now leave the first letter "e" and combine letters "he" with the next letter "h" to form "heh" is it the substring we are looking for?现在留下第一个字母“e”并将字母“he”与下一个字母“h”组合起来形成“heh”这是我们正在寻找的子串吗? - no
- 不
now leave the first letter "h" and combine letters "eh" with the next letter "e" to form "ehe" is it the substring we are looking for ?现在留下第一个字母“h”并将字母“eh”与下一个字母“e”组合起来形成“ehe”这是我们正在寻找的子字符串吗? yes
是的
do it till the end of the string and count number of "yes"s直到字符串结束并计算“是”的数量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.