【发布时间】:2018-08-09 08:39:25
【问题描述】:
我在 python 中有一个列表/数组 str4,我想用一个我坚信是 int 的变量来访问它,因为我用函数 isdigit() 对其进行了测试strong> 并且我还进行了手动调试并检查了所有选项是否正确显示唯一的数字。
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 告诉我它是一个字符串? 我做错了什么?
【问题讨论】:
-
你刚刚打开文件,你从来没有读过它
-
'2'和2不是一回事。它们都是数字,但第一个是string,第二个是integer。line默认是string,因为它是从文件中读取的。num最终成为line的一部分,所以它也是string。 -
在第 34 行之前使用 int(num) 将 num 转换为整数
标签: python python-2.7 file integer typeerror