我想計算字符串s中發生「bob」的次數。我寫的代碼是:python - 計算字符串失敗的連續字母集合的程序
s = 'qwbobthghdeerxybobhjkhgkjgbob'
num = 0
count = 0
for char in s:
if char == 'b':
letter = s[num+1]
if letter == 'o':
letter = s[num+2]
if letter == 'b':
count = count + 1
num += 1
print('Number of times bob occurs is:' + str(count))
運行代碼給出了錯誤:
Traceback (most recent call last):
File "C:/Python27/practice.py", line 6, in <module>
letter = s[num+1]
IndexError: string index out of range
變量num的殼價值出來作爲
>>>num
28
這怎麼可能?