Python TypeError:' str' object不能解释为整数

时间:2017-12-25 11:32:55

标签: python python-3.x

我有这段代码:

            if current_ins[0] == "REPEAT":
                for i in range(current_ins[1]):
                    if last_ins != "":
                        instructions.append(last_ins)
                        if delay != -1:
                            instructions.append(["DELAY", delay])
                    else:
                        print ("ERROR: REPEAT can't be the first instruction")
                        sys.exit(-1)

,不幸的是我收到了这个错误:

Duck Encoder 0.1.1 by Roger Serentill & GoldraK
Traceback (most recent call last):
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 379, in <module>
    p.compile(sys.argv)
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 56, in compile
    instructions = self.__read_file()
  File "D:\devloc\Encoders-decoders\USB-Rubber-Ducky-master\Encoder\Encoder.py", line 263, in __read_file
    for i in range(current_ins[1]):
TypeError: 'str' object cannot be interpreted as an integer

我该怎么办?

BTW,我正在使用Python3。

2 个答案:

答案 0 :(得分:0)

尝试range(len(current_ins[1])):range(int(current_ins[1])):。这取决于current_ins [1]中的内容。

答案 1 :(得分:0)

我想你正试图做这样的事情: -

Inst1
Inst2
REPEAT 5

现在,您尝试重复之前的说明,无论您使用Repeat指定的“数字”。

您可以确定将其转换为int,例如int(currenct_inst[1]),但这真的很暧昧。根据{{​​1}}我建议你更明确,或许

zen of python

如果您想处理像if current_instruction[0] = repeat: # strip here removes the leading and trailing whitespace times_repeat = int(current_instrucitons[1].strip()) 这样的指令,那么您应该看一下异常处理。

如果您有兴趣,请查看: - https://www.programiz.com/python-programming/exception-handling