对于新手来说,这是一个极其低级还不容易发现的错误!!!
出现报错:TypeError: byte indices must be integers or slices, not tuple
或者TypeError: string indices must be integers
用两个例子来解释:
(1)
def test_add(a, b):
return a+b
test(1,1)
结果是 2
(2)
def test_slice(a, b):
s = 'China'
return s[a, b]
test_slice(2,4)
结果:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-29-a1aa0e144519> in <module>
3 return s[a, b]
4
----> 5 test_slice(2,4)
<ipython-input-29-a1aa0e144519> in test_slice(a, b)
1 def test_slice(a, b):
2 s = 'China'
----> 3 return s[a, b]
4
5 test_slice(2,4)
TypeError: string indices must be integers
改正:
def test_slice(a, b):
s = 'China'
return s[a:b]
test_slice(2,4)
结果:‘in’
Python列表的切片操作是 lst[a:b]
,不要犯低级错误写成 lst[a,b]