我試圖做一個程序,搜索字符串'鮑勃',並打印出現的次數。 下面是代碼:字符串索引超出範圍錯誤for循環
s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s)) :
u = s[i]
if u == 'o':
g = i
if g != 0 and g != len(s) :
if (s[g+1]) == 'b' and (s[g-1]) == 'b': #this line is the problam
numbob += 1
print("Number of times bob occurs is: " +str(numbob))
我得到的字符串索引超出範圍的錯誤,我似乎無法修復它。任何建議
你在找s.count('bob')嗎? – Leo
這似乎是一個重複:http://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string 這提供了一個更好的方式來做你所做的這樣做。 :) – Kieran
請注意''bobob'.count('bob')== 1',不是人們所希望的。 – BallpointBen