原文: TypeError: 'int' object is not subscriptable [Solved Python Error]

当你试图把一个整数当作一个可下标的对象时,就会出现 Python 错误 “TypeError: 'int' object is not subscriptable”。

在 Python 中,一个可下标的对象是你可以添加下标或可迭代的对象。

为什么会出现 “TypeError: 'int' object is not subscriptable Error” 错误

你可以在一个字符串、列表、元组、甚至字典上进行迭代,但不可能在一个整数或数字集上迭代。

所以,如果你得到这个错误,说明你试图在一个整数上迭代,或者你把一个整数当作一个数组。

在下面的例子中,我把出生日期(dob 变量)写成了 ddmmyy(日期+月份+年份)格式。我试图得到出生的月份,但没有成功。它抛出了错误 “TypeError: 'int' object is not subscriptable”:

dob = 21031999
mob = dob[2:4]

print(mob)

# Output: Traceback (most recent call last):
#   File "int_not_subable..py", line 2, in <module>
#     mob = dob[2:4]
# TypeError: 'int' object is not subscriptable

如何修复 “TypeError: 'int' object is not subscriptable” 错误

要解决这个错误,你需要将整数转换为可迭代的数据类型,例如字符串。

如果你得到这个错误是因为你把某个东西转换成了整数,那么你需要把它改回原来的样子,例如,字符串、元组、列表,等等。

在上面那个出错的代码中,我通过将 dob 变量转换为字符串,使其正常运行:

dob = "21031999"
mob = dob[2:4]

print(mob)

# Output: 03

如果你在将某样东西转换为整数后得到错误,这意味着你需要将它转换回字符串或保持原样。

在下面的例子中,我写了一个 Python 程序,以 ddmmyy 的格式打印出出生日期,但是它返回了一个错误:

name = input("What is your name? ")
dob = int(input("What is your date of birth in the ddmmyy order? "))
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, \nYour date of birth is {dd} \nMonth of birth is {mm} \nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Traceback (most recent call last):
#   File "int_not_subable.py", line 12, in <module>
#     dd = dob[0:2]
# TypeError: 'int' object is not subscriptable

看了一下代码,我想起输入返回的是一个字符串,所以我不需要把用户的出生日期输入的结果转换成一个整数。这就解决了这个错误:

name = input("What is your name? ")
dob = input("What is your date of birth in the ddmmyy order? ")
dd = dob[0:2]
mm = dob[2:4]
yy = dob[4:]
print(f"Hi, {name}, \nYour date of birth is {dd} \nMonth of birth is {mm} \nAnd year of birth is {yy}.")

#Output: What is your name? John Doe
# What is your date of birth in the ddmmyy order? 01011970
# Hi, John Doe,
# Your date of birth is 01
# Month of birth is 01
# And year of birth is 1970.

总结

在这篇文章中,你了解了 Python 中 “TypeError: 'int' object is not subscriptable” 错误的原因以及如何解决这个问题。

如果你得到这个错误,这意味着你把整数当作可迭代的数据。整数不是可迭代的,所以你需要使用一个不同的数据类型,或者将整数转换成可迭代的数据类型。

而如果错误的发生是因为你把某样东西转换成了整数,那么你就需要把它改回原本的可迭代的数据类型。

谢谢你阅读本文。