python - 计算字符串中一组连续字母失败的程序

时间:2015-10-17 15:18:49

标签: python string

我想计算字符串s中'bob'出现的次数。我写的代码是:

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

shell中变量num的值为

>>>num
28

这怎么可能?

3 个答案:

答案 0 :(得分:3)

内置函数count

更容易
s = 'qwbobthghdeerxybobhjkhgkjgbob'
s.count('bob')

答案 1 :(得分:2)

如上所述,伯爵会给你答案。

代码使索引超出范围的问题是因为当它到达最后一个&#34; b&#34;在字符串s中,此代码:

letter = s[num+1]

尝试

letter = s[28+1]

给你

letter = s[29]

因此发生异常。

一个简单的解决方法是在字符串中剩下少于3个字符时停止检查。

答案 2 :(得分:2)

count方法返回obj在变量中出现的次数。

s ='qwbobthghdeerxybobhjkhgkjgbob'

print s.count('bob')