2016-09-20 122 views
-1

我試圖做一個程序,搜索字符串'鮑勃',並打印出現的次數。 下面是代碼:字符串索引超出範圍錯誤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)) 

我得到的字符串索引超出範圍的錯誤,我似乎無法修復它。任何建議

+3

你在找s.count('bob')嗎? – Leo

+1

這似乎是一個重複:http://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-string 這提供了一個更好的方式來做你所做的這樣做。 :) – Kieran

+0

請注意''bobob'.count('bob')== 1',不是人們所希望的。 – BallpointBen

回答

1

使用

for i in range(len(s)-1) 

g!=len(s)-1 

len()爲您提供了字符的總數,這將是字符的最後一個接一個索引,因爲索引從0開始。

如果您使用

01您可以擺脫 if g!=0 and g!=len(s)部分
for i in range(1,len(s)-1) 
+0

它工作!感謝您的快速回答,我無法強調這一點 –

+1

@ sudomakeinstall2感謝您的編輯。現在看起來好多了。 :) – SilentLupin

0

當你做你的病情:

if (s[g+1]) == 'b' and (s[g-1]) == 'b': 

在您的字符串的最後一個元素,這是不可能做到s[g+1],因爲它超出了字符串。

所以你必須在結束之前完成你的循環。像這樣的例子:

for i in range(len(s)-1) : 
相關問題