简体   繁体   English

我为什么会收到此错误TypeError:列表索引必须是整数或切片,而不是str

[英]Why am I getting this error TypeError: list indices must be integers or slices, not str

I've created a list of characters named 'char' I thought this code would compare the user input but I am getting a TypeError 我创建了一个名为“ char”的字符列表,我认为这段代码可以比较用户输入,但是出现TypeError

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.

相关问题 我不断收到此错误:列表索引必须是整数或切片,而不是 str - I keep getting this error: list indices must be integers or slices, not str 为什么我会收到类型错误:在调用函数并传递字典时,列表索引必须是整数或切片,而不是 str - Why am I getting a Type error: list indices must be integers or slices, not str, while calling a function and passing a dictionary 检索ID并获取TypeError:列表索引必须是整数或切片,而不是str - Crawling IDs and getting TypeError: list indices must be integers or slices, not str 获取 TypeError:列表索引必须是整数或切片,而不是 str - Getting a TypeError: list indices must be integers or slices, not str 我对字符串和整数有些困惑,并且不断收到此错误:TypeError:列表索引必须是整数或切片,而不是str - I'm a little confused with strings and integers, and I keep getting this error: TypeError: list indices must be integers or slices, not str “TypeError:list indices必须是整数或切片,而不是str” - “TypeError: list indices must be integers or slices, not str” TypeError:列表索引必须是整数或切片,而不是 str - TypeError: List indices must be integers or slices and not str 类型错误:列表索引必须是整数或切片,而不是 str - TypeError: list indices must be integers or slices, not str “TypeError:列表索引必须是整数或切片,而不是 str” - "TypeError: list indices must be integers or slices, not str" TypeError:列表索引必须是整数或切片而不是 str - TypeError: list indices must be integers or slices not str
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM