我在python中有一个list / array str4,我想用变量访问它,我强烈认为它是一个int,因为我用函数isdigit()测试它,我也进行了手动调试并检查所有选项是否出来正确的唯一号码。
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]
上面的代码用于调试,我的问题是在str4 [num]中,上面代码的结果是:
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
为什么num是一个数字,但python告诉我它是一个字符串?我究竟做错了什么?
翻译永远不会错......
更严重的是,您将num作为子字符串,因此它是一个字符串。如果要将其用作字符串索引,则必须将其转换为int:
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
您检查字符串posArray是否为数字:
if posArray.isdigit():
num = posArray
但你没有把它转换成数字,就像这样:
if posArray.isdigit():
num = int(posArray)
请查看下面的评论,查看您的代码。从底部到顶部阅读它,以了解如何轻松调试自己的代码;思考过程是什么。
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
我们上面显示的是,最终,num
将与line
(str
)属于同一类型,因此,不能用于index
任何东西。它必须首先通过int
转换为int(num)
另一个解决方案是
num = posArray
做:
print str4[int(num)])