Python 索引报错:TypeError: byte indices must be integers or slices, not tuple

文章目录

  • 1. 问题
  • 2. 问题再现
  • 3. 反思

对于新手来说,这是一个极其低级不容易发现的错误!!!

1. 问题

出现报错:TypeError: byte indices must be integers or slices, not tuple或者TypeError: string indices must be integers

2. 问题再现

用两个例子来解释:
(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’

3. 反思

Python列表的切片操作是 lst[a:b],不要犯低级错误写成 lst[a,b]

你可能感兴趣的:(#,Python,疑难杂症)