首页 > 解决方案 > Python“TypeError:'int'对象不可下标”

问题描述

我需要一些帮助。试图找出问题所在。

        parse = json.loads(phoneget.text)
        phoneNUM = parse["tel"] # gets phone number
        phoneID = parse["idNum"] # gets id number
        print(sms_config.key) # ignore this
        print("Parse complete, here is your result:") # ignore this
        print("Phone:", parse["tel"]) # prints phone number
        print("ID:", parse["idNum"]) # prints id number
        print(phoneget) # prints url - ignore this

        # Slice the first number off (country code)
        phoneNUM = phoneNUM
        print(phoneNUM[1:])
Output: TypeError: 'int' object is not subscriptable
Desired output: 2345678900

标签: python

解决方案


错误消息的第一部分是:TypeError,它说明了我们的错误类型。当您尝试对不支持该操作的值执行操作时,会引发 TypeError。错误消息的第二部分告诉我们 TypeError 的原因。这意味着我们正在处理一个整数(它是一个整数),就像一个可下标的对象。整数不是可下标的对象。只有包含其他对象(如字符串、列表、元组和字典)的对象是可下标的,即我们可以使用索引从中检索值。因此,为了将整数值用作可下标对象,我们需要将其类型转换为字符串或任何其他可下标对象。因此,使用: print(str(phoneNUM)[1:])


推荐阅读