[英]Checking the number of times a string occurs in another string
Currently, I have a code that tells me if a string is in another string.目前,我有一个代码可以告诉我一个字符串是否在另一个字符串中。 However, I do not want it to stop the moment it finds the string.
但是,我不希望它在找到字符串的那一刻停止。 Instead, I want it to continue and tell me the total number of time it duplicates.
相反,我希望它继续并告诉我它重复的总次数。 Eg.
例如。 "110010","10" Expected answer: 2 Given answer: 1
"110010","10" 预期答案:2 给出答案:1
Below is my code.下面是我的代码。
def occurence(s1,s2):
count == 0
if s2 in s1:
count += 1
return count
You can just use the func count
.您可以只使用 func
count
。
In your case, use : s1.count(s2)
在您的情况下,请使用:
s1.count(s2)
You could just loop through the s1 with slices of size of the s2 and count if the slice is equal to s2您可以使用 s2 大小的切片循环遍历 s1 并计算切片是否等于 s2
s1 = '110010'
s2 = '10'
count = 0
for i in range(0,len(s1)-len(s2)+1):
if s1[i:i+len(s2)] == s2:
count += 1
print(count)
which outputs: 2输出:2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.