首页 > 解决方案 > TypeError: 'int' 对象不可下标,因为 y=int(x[2:4])

问题描述

我想将一个 6 位数字和它的 2 个中心数字相乘,但是在发生计算的循环中会引发异常:

TypeError: 'int' 对象不可下标,因为 y=int(x[2:4])

TypeError: 'int' object is not subscriptable because of the
y=int(x[2:4])

我能做些什么来纠正这个错误?

x=input("Enter a numer of at least 6 digits: ")
while len(x)!=6:
    x=input("Enter a numer of at least 6 digits: ")

x1=int(x)
z=int(input("How many times do you want to repeat the procces? "))
r=range(z)

for i in r:
    y=int(x[2:4])
    x=y*x1
    print(x)

标签: pythonpython-3.x

解决方案


您只需转换xstr,提取中间数字,然后将它们转换回int.

修改您的代码如下:

for i in r:
    y=int(str(x)[2:4])
    x=y*x1
    print(x)

编辑

正如@byxor 所指出的,您不应更改变量的类型x

for i in r:
    y = int(x[2:4])
    x = str(y*int(x))
    print(x)

边注

尽管您想获得中间的 2 位数字并将它们与x时间相乘z。您的号码x可能会超过 6 位,您将不再选择中间的 2 位数字。此解决方案最多可以修复您的错误。


推荐阅读