for循环中的字符串索引超出范围错误

2024-09-29 19:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个程序,在字符串中搜索“bob”并打印它出现的次数。 代码如下:

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) )

我得到字符串索引超出范围的错误,我似乎无法修复它。有什么建议吗


Tags: and字符串代码in程序forlenif
3条回答

我的解决办法比你的简单。而不是把字母“b”“o”“b”分开。切片字符串s

countbob=0
bob='bob'
for i in range(len(s)):
       bob2=s[i:i+3]
       if bob2 == bob:
               countbob +=1
print ("Number of times bob occurs is: " + str(countbob))

使用

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

或者

^{pr2}$

len()给出字符总数,这将是最后一个字符之后的索引,因为索引从0开始。在

如果您使用

^{3}$

当你提出你的条件时:

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

在字符串的最后一个元素,不可能执行s[g+1],因为它超出了字符串。在

所以你必须在结束前完成你的循环。例如:

^{pr2}$

相关问题 更多 >

    热门问题