[英]Why am I getting this error TypeError: list indices must be integers or slices, not str
[英]I am getting python error TypeError: String indices must be integers, not str
以下是我從JSON響應中獲得的字典
{u'definitions': [{u'text': u'One venerated for experience, judgment, and wisdom.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Having or exhibiting wisdom and calm judgment.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Proceeding from or marked by wisdom and calm judgment: sage advice. ', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Archaic Serious; solemn.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various plants of the genus Salvia, especially S. officinalis, having aromatic grayish-green, opposite leaves. Also called ramona.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'The leaves of this plant used as a seasoning.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Any of various similar or related plants in the mint family.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}, {u'text': u'Sagebrush.', u'attribution': u'from The American Heritage\xae Dictionary of the English Language, 4th Edition'}]}
我正在嘗試使用此代碼語句訪問前兩個“文本”:
text1 = [body["definitions"][0]["text"],
body["definitions"][1]["text"]]
我得到了我需要的琴弦。
但是實際的問題是,當我在樹莓派2上運行相同的代碼時,出現以下錯誤
TypeError:字符串索引必須是整數,而不是str
任何幫助,將不勝感激。
body["definitions"]
返回一個字符串,說“ hello”,因此,如果您編寫:
body["definitions"]["0"]
等效於:
"hello"["0"]
產生錯誤:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
但是,如果您寫:
"hello"[0]
你得到:
'h'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.