2015-10-17 100 views
0

我想计算字符串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 

这怎么可能?

回答

3

它具有内置功能count简单:

s = 'qwbobthghdeerxybobhjkhgkjgbob' 
s.count('bob') 
2

如前所述,计数给你答案。

与您的代码给指数超出范围的问题,因为当它到达字符串s,此代码的最后“B”:

letter = s[num+1] 

尝试

letter = s[28+1] 

,让你

letter = s[29] 

因此发生异常。

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

2

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

S = 'qwbobthghdeerxybobhjkhgkjgbob'

打印s.count( '鲍勃')

相关问题