首页 > 其他分享 >关于pthon中-字符串处理时-TypeError: string indices must be integers-的原因分析及处理

关于pthon中-字符串处理时-TypeError: string indices must be integers-的原因分析及处理

时间:2022-08-17 23:22:27浏览次数:71  
标签:integers pthon TypeError string indices 字符串 字典

今天笔者将一串如下样式的json格式的字符串,如下赋值给一个变量时

{
    "Images": [
        {
            "Architecture": "x86_64",
            "CreationDate": "2022-08-16T10:51:34.000Z",
            "ImageId": "ami-035c4c35b473bb123",
            "ImageLocation": "904520594201/QQ-5201351-backup",
            "ImageType": "machine",
            "Public": false,
            "OwnerId": "904520594201",
            "PlatformDetails": "Red Hat Enterprise Linux",
            "UsageOperation": "RunInstances:0010",
            "State": "available",
            ............ 省略其余部分 ............
       }
    ]
}

字符串看着像python中的字典格式一样,于是突发其想,尝试去访问字符串变量的["Images"],

结果报错:TypeError: string indices must be integers

当然从报错也可以看出,要求访问字符串时indices 必须是一个整数,其实也不难理解,字符串只是长得像字典,但终究不是字典

于是想到了之前也多次用到的解决方法:先将字符串转换成字典格式,

这样就需要导入json模块, 使用json.loads(str_var),转换后,就可以通过上面的方式进行访问和获取想要的数据了即可解决~

 

 

尊重别人的劳动成果 转载请务必注明出处:https://www.cnblogs.com/5201351/p/16597194.html

 

标签:integers,pthon,TypeError,string,indices,字符串,字典
From: https://www.cnblogs.com/5201351/p/16597194.html

相关文章