[英]Finding how many times a substring appears in a given string
s = 'This is a bad bad example'
sub = 'bad'
start = 0
count = 0
while True:
start = s.find(sub,start) + 1
if start >= 0:
count = count+1
else:
break
print 'The number of times bad appears in the given string is: ' + str(count)
這就是我嘗試過的。 我已經嘗試過自己調試它,但是我無法弄清楚哪里出了問題。 我使用了find()
函數不正確嗎?
不應太難,最好的部分是python消除了遍歷所有內容的需要!
嘗試這個:
>>> a = "this is a bad bad example"
>>> a.count('bad')
2
a.count(b)
返回b
在字符串或列表a
中出現的次數。
編輯要解決您的代碼:
while True:
start = s.find(sub,start) + 1
if start >= 0:
count = count+1
else:
break
您正確使用了find()
,但是當沒有更多bad
s時,它將返回-1
,然后將其添加到1(同樣由於0索引而正確),但是請檢查start >= 0
將始終返回true,因為-1(錯誤的結果)將變為0(正的結果)
嘗試這個:
start = -1 # start at -1 now, you'll see why...
while True:
start = s.find(sub,start + 1)
if start >= 0:
count = count+1
else:
break
因此,您要在find()
調用中解決一次性錯誤,而不是將其存儲在終止條件中。 更好的是:
while start >= 0:
start = s.find(sub,start+1)
count += 1
我可能是錯的,但是如果子字符串“重疊”,我認為count不能像您期望的那樣工作。 例如:
s1="dadad"
s2='dadsdad'
sub="dad"
s1.count(sub) #1
s2.count(sub) #2
這是我的解決方法:
def overlapping_substring_count(string,sub_string):
l=len(sub_string)
count=0
for i in range(len(string)-len(sub_string)+1):
if(string[i:i+len(sub_string)] == sub_string ):
count+=1
return count
s1='dadad'
s2="dad"
print(overlapping_substring_count(s1,s2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.