Python错误:TypeError: string indices must be integers
生活随笔
收集整理的這篇文章主要介紹了
Python错误:TypeError: string indices must be integers
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在項目遇到一個錯誤 :
TypeError: string indices must be integers
?
由于是返回的接口數(shù)據(jù),所以一時也分辨不出是哪里的錯,然后我就還原了這樣的場景:
?
unicode_str = u'abcd' print unicode_str[2] print unicode_str['mykey']?
讀取一個unicode編碼的字符串的一個不存在的屬性,見第三行,然后就會出現(xiàn)上面的錯誤
?
所以在讀取字典的時候,最好先判斷類型,然后再查看它是否已經(jīng)有這樣的屬性:
?
type(mydict) == type({}) #檢查不是字典
如果是字典,再看看有沒有這樣的屬性:mydict.has_key('mykey') ?
總結(jié)
以上是生活随笔為你收集整理的Python错误:TypeError: string indices must be integers的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 集合List、Set、Hash
- 下一篇: websocket python爬虫_p