【问题标题】:Why am I getting this error TypeError: list indices must be integers or slices, not str为什么我收到此错误 TypeError: list indices must be integers or slices, not str
【发布时间】:2017-04-25 04:42:09
【问题描述】:

我创建了一个名为“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: ")

【问题讨论】:

  • 你能提供错误的文本吗?
  • i 是一个字符串。您不能将其用作char[i] 中的索引(即i 必须是整数或切片。)
  • i 已经是char 中的项目。做if sorubir.upper() == i

标签: python arraylist typeerror


【解决方案1】:

for i in char 已经引用了数组中的实际字符。我相信你认为i 是它的索引。那将改为for i in range(0, len(char)),我将在其中获取索引值。

在您当前的代码中,只需将sorubir.upper() == char[i] 更改为sorubir.upper() == i 就可以了!

【讨论】:

  • 嗯.. 你的char 列表是什么样的?都是大写吗?
  • 谢谢!这解决了我的问题,但现在我有另一个问题。当我从列表中输入一个有效值时,代码会继续执行 else 语句,就好像它并没有真正将它与列表进行比较。当我尝试 for i in range (0,char) 时,它说“TypeError:'list' 对象不能被解释为整数”
  • 大写姓名和姓氏。和他们之间的空间有关系吗?
  • 1. TypeError 问题 - 哎呀,我现在已经更正了(缺少 len())。 2. 你能给我举个例子吗,比如`["BOB", "JENNY"]?
  • char = ['EMRE CAKIR',REYHAN BOZTAS','NILUFER SAGLAM']
【解决方案2】:

在做

for i in char:

除非它是一个数字列表,否则将返回存储在该索引中的数据。

例如你可以这样做

char['foo']

这将返回您遇到的错误类型。

改为尝试使用

for i in range(len(char)):

这将为列表的每个索引返回一个整数。

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 2022-08-17
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2023-02-07
    • 2013-09-26
    相关资源
    最近更新 更多