[英]Why am I getting this error TypeError: list indices must be integers or slices, not str
while True:
sorubir = input("Enter a character name: ")
for i in char:
if sorubir.upper() == char[i]:
print (sorubir)
else:
sorubir = input("Try again. Enter a character name: ")
for i in char
already refers to the actual character in the array. for i in char
已经引用了数组中的实际字符。 I believe you thought i
to be its index. 我相信你以为i
是它的索引。 That would be written instead as for i in range(0, len(char))
, where i would take an index value. 它将被替换为for i in range(0, len(char))
中的i,其中i将采用一个索引值。
In your current code, simply changing sorubir.upper() == char[i]
to sorubir.upper() == i
should do the trick! 在您当前的代码中,只需将sorubir.upper() == char[i]
更改为sorubir.upper() == i
就可以解决问题!
Doing 在做
for i in char: 对于我在char中:
Unless it's a list of numbers will return the data stored in that index. 除非是数字列表,否则将返回存储在该索引中的数据。
For example you could be doing 例如,您可能正在做
char['foo'] 字符['foo']
That will return the type of error you were getting. 这将返回您得到的错误类型。
Instead try using 而是尝试使用
for i in range(len(char)): 对于范围内的我(len(char)):
This will return an integer for each index of the list. 这将为列表的每个索引返回一个整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.