'bob'の文字列を検索して表示される時間を表示するプログラムを作成しようとしています。文字列インデックスが範囲外です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'であり、2つではないことに注意してください。 – BallpointBen