python - 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)
解决方案
您只需转换x
为str
,提取中间数字,然后将它们转换回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 位数字。此解决方案最多可以修复您的错误。
推荐阅读
- javascript - 日期字符串转换浏览器与夏令时的区别
- amazon-web-services - 具有基于授权上下文的自定义声明的 AWS Cognito 令牌
- php - 如何在 php 错误语句中使用 span 标签
- javascript - 通过单击行将表行滚动到 div 的顶部
- xamarin.ios - Restsharp - 无法获取错误响应正文
- python - 在 $in 中添加模式,并聚合
- android - 为什么 Android Studio 3.2.1 无法正确解释文件内容 - 甚至没有关闭 - 对于我的一半项目类文件?
- scala - @specialized 补充资料
- python - Pandas:删除数据框中的重复行
- powershell - azure devops 在 powershell 中使用 dbatools 构建任务警告