[英]How to count number of occurrences of a substring inside a string in Python?
我正在嘗試編寫一個代碼片段,請求用戶輸入字符串s
然后輸入子字符串ss
。 然后程序必須計算s
中ss
出現的次數。 例如,如果用戶輸入s = 'azcbobobegghakl'
和ss = '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 提到的,它使用了他所謂的滑動窗口方法
我們取子字符串的長度並檢查它是否在每次迭代的字符串“窗口”中:
is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1
您需要采用滑動窗口方法來獲取字符串中子字符串的計數。
例子:
字符串:“呵呵”
子字符串:“嗯”
從前 3 個(因為子串的長度是 3 個)字母“ehe”開始——它是我們要找的子串嗎? - 是的。
現在留下第一個字母“e”並將字母“he”與下一個字母“h”組合起來形成“heh”這是我們正在尋找的子串嗎? - 不
現在留下第一個字母“h”並將字母“eh”與下一個字母“e”組合起來形成“ehe”這是我們正在尋找的子字符串嗎? 是的
直到字符串結束並計算“是”的數量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.