Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用变量切片字符串,TypeError:字符串索引必须是整数_Python - Fatal编程技术网

Python 使用变量切片字符串,TypeError:字符串索引必须是整数

Python 使用变量切片字符串,TypeError:字符串索引必须是整数,python,Python,我正在尝试编写一个脚本,在给定字符串中查找子字符串“bob”。我认为字符串切片是一种很好的方法,但我得到了“TypeError:字符串索引必须是整数”。我对此感到困惑,因为据我所知,我用作索引的两个变量都是整数 而且,即使这段代码不是一种有效的方法,我也很好奇为什么我在使用变量作为索引时遇到了问题,因为我所有的谷歌搜索都发现了这是一件可以做的事情 s = 'azcbobobegghakliia' bob = 'bob' startindex = 0 endindex = 2 numBob =

我正在尝试编写一个脚本,在给定字符串中查找子字符串“bob”。我认为字符串切片是一种很好的方法,但我得到了“TypeError:字符串索引必须是整数”。我对此感到困惑,因为据我所知,我用作索引的两个变量都是整数

而且,即使这段代码不是一种有效的方法,我也很好奇为什么我在使用变量作为索引时遇到了问题,因为我所有的谷歌搜索都发现了这是一件可以做的事情

s = 'azcbobobegghakliia'

bob = 'bob'
startindex = 0
endindex = 2
numBob = 0

while len(s) > endindex:
    if s[startindex,endindex] == 'bob':
        numBob += 1
        startindex += 1
        endindex += 1
print(numBob)

我希望它打印2,因为“bob”在这个字符串中包含两次(…bobob…)。实际输出是“TypeError:字符串索引必须是整数”

默认情况下,逗号分隔的变量构成元组。您希望使用
来制作切片

更详细的解释:
a[b,c]
相当于
a[(b,c)]
,也就是说,
a
用元组
(b,c)
索引。要获取从
b
c
的元素,需要
a[b:c]