我正在尝试制作一个程序,在字符串中搜索“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) )
我得到字符串索引超出范围的错误,我似乎无法修复它。有什么建议吗
我的解决办法比你的简单。而不是把字母“b”“o”“b”分开。切片字符串s
使用
或者
^{pr2}$len()
给出字符总数,这将是最后一个字符之后的索引,因为索引从0开始。在如果您使用
^{3}$当你提出你的条件时:
在字符串的最后一个元素,不可能执行
s[g+1]
,因为它超出了字符串。在所以你必须在结束前完成你的循环。例如:
^{pr2}$相关问题 更多 >
编程相关推荐