字符串的索引必须是整数。这意味着当你要获得像字符串一样的可迭代对象时,你必须用一个数值来做。如果你要访问一个字典中的元素,要确定你是在访问字典本身,而不是字典中的一个键。
类型错误:字符串的索引必须是整数
typeerror: string indices must be integers 表示我们正试图使用字符串索引而不是整数索引来访问一个可迭代对象的值。迭代对象是使用数字进行索引的。因此,当你试图使用字符串值获取一个可迭代对象时,将会返回一个错误。
在 Python 中,我们可以使用整数作为索引来访问列表元素:
list = ["PS5", "Xbox Series X", "Nintendo Switch"]
print(list[1])
这是一个字符串的列表。要访问这个列表中的第二个项目,我们需要通过它的索引值来引用它,然后我们就得到了这个项目。
输出
Xbox Series X
我们不能用字符串访问这个列表项。否则就会返回 TypeError。
这对列表来说很好,但是让我们创建一个 dictionary 并访问它的元素:
data = {
"console": "PS5",
"exclusive": "Spiderman Miles Morales",
"genre": "Superhero"
}
让我们遍历这个 dictionary 中的所有值并打印它们:
for ele in data:
print("Console Name: " + ele["console"])
print("Exclusive Game: " + ele["exclusive"])
print("The Genre is: " + str(ele["genre"]))
输出
Traceback (most recent call last):
File "/Users/krunal/Desktop/code/pyt/database/app.py", line 13, in <module>
print("Console Name: " + ele["console"])
TypeError: string indices must be integers
我们得到 TypeError:字符串索引必须是整数。TypeError 之所以出现,是因为我们试图用字符串索引而不是整数来访问我们字典中的值。
解决了:字符串索引必须是整数
我们代码中的主要问题是,我们在 "data "字典中的每个键上进行迭代。ele"的值始终是字典中的一个键。它不是我们字典中的一个记录。让我们试着打印出我们字典中的 "ele"。
data = {
"console": "PS5",
"exclusive": "Spiderman Miles Morales",
"genre": "Superhero"
}
for ele in data:
print(ele)
输出
console
exclusive
genre
你可以看到,我们得到了字典中的键。我们不能用 "ele" 来访问我们字典中的值。ele["console"] 等于 "ele" 里面的 "console" 的值,也就是 "console"。这对 Python 来说是没有意义的。你不能用另一个字符串访问一个字符串中的值。
为了解决TypeError:字符串索引必须是整数;我们应该引用我们的字典而不是 "ele"。我们可以用一个字符串来访问我们字典中的元素。这是因为 dictionary 的键可以是字符串。我们不需要一个for 循环来打印出每个值。
data = {
"console": "PS5",
"exclusive": "Spiderman Miles Morales",
"genre": "Superhero"
}
print("Console Name: " + data["console"])
print("Exclusive Game: " + data["exclusive"])
print("Game Genre: " + (data["genre"]))
输出
Console Name: PS5
Exclusive Game: Spiderman Miles Morales
Game Genre: Superhero
我们成功地打印了我们的 dictionary 中的每个值。这是因为我们不再试图用迭代器 ("ele") 中的字符串值访问我们的 dictionary。
本教程就到此为止。