简体   繁体   中英

Python -> TypeError: list indices must be integers, not str

I have a list/array str4 in python, I want to access it with a variable which I strongly believe is an int because I test it with the function isdigit() and I also made a manual debug and checked that all the option come out correctly with the only number.

temp = "variableX"
file2 = open('file.txt','r')
for line in file2:
  if line.find(temp) =! -1:
    posArray = line.split(temp)[1][1:3]
    if ")" in posArray:
      posArray = posArray[:-1]
    if posArray.isdigit():
      num = posArray
      print temp+"("+num+")"
      print num
      print str4[num]

The above code is used to debug, my problem is in the str4[num] , the result of the above code is:

variableX(1)
1
"this is position 1"
Traceback (most recent call last):
  File "orderList.py", line34, in <module>
    print str4[num]
TypeError: list indices must be integers, not str

Why num is a digit but python tells me it is a string? What am I doing wrong?

You checked if string posArray is a digit:

  if posArray.isdigit():
      num = posArray

But you did't convert it to digit, like so:

  if posArray.isdigit():
      num = int(posArray)

Take a look your code with my comments below. Read it from the bottom to the top to get an idea on how you can easily debug your own code; what the thinking process is.

temp = "variableX"
file2 = open('file.txt','r')  # which is a file, so `line` is `string` - CASE CLOSED
for line in file2:  # and `line` is a result of looping through `file2`
  if line.find(temp) =! -1:
    posArray = line.split(temp)[1][1:3]  # and `posArray` is a part of `line`
    if ")" in posArray:
      posArray = posArray[:-1]  # ok, `posArray` is a part of `posArray`
    if posArray.isdigit():  # `posArray` contains digits only but that doesn't help really, so does "123"..
      num = posArray  # ok, so `num` is whatever `posArray` is
      print temp+"("+num+")"
      print num
      print str4[num]  # here is the Error so we start here and work backwards

What we show above is that ultimately, num will be of the same type as line ( str ) and as a result, cannot be used to index anything. It must be converted to int first by doing int(num)

The interpretor is never wrong...

More seriously, you get num as a substring so it is a string. You must convert it into in int if you want to use it as a string index:

  num = int(posArray)          # ok num is now an int
  print temp+"("+str(num)+")"  # must use str to concat it with strings
  print num, type(num), posArray, type(posArray) # num is int, posArray is string
  print str4[num]              # now fine

Another solution is after

num = posArray

do:

print str4[int(num)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM