Python 将列表元素(字符串)与字符进行比较,但获取有关整数的错误消息

Python 将列表元素(字符串)与字符进行比较,但获取有关整数的错误消息,python,Python,为什么这行代码 if (inputlist[x]) is ("r"): 给我这个错误信息 if (inputlist[x]) is ("r"): TypeError: string indices must be integers 所有列表元素都是单个字符,字符串类型。我无法想象错误的整数部分是从哪里来的 据我所知,x很可能是导致您出现问题的原因。为了使用字符串[x],x代表索引位置,因此x必须是整数。如果x不是整数,您将得到TypeError。看起来,您的inputlist变量指向字符串对

为什么这行代码

if (inputlist[x]) is ("r"):
给我这个错误信息

if (inputlist[x]) is ("r"):
TypeError: string indices must be integers

所有列表元素都是单个字符,字符串类型。我无法想象错误的
整数部分是从哪里来的

据我所知,x很可能是导致您出现问题的原因。为了使用字符串[x],x代表索引位置,因此x必须是整数。如果x不是整数,您将得到TypeError。

看起来,您的
inputlist
变量指向字符串对象,要访问单个字符,您需要使用
integer
作为索引

inputlist[2] = # Something
您可能正在执行以下操作:

inputlist = "hello world"
for x in inputlist:
    if (inputlist[x]) is ("r"):
        print("yes")
    else:
        print("no")
inputlist = "hello world"
for x in inputlist:
    if x == "r":
        print("yes")
    else:
        print("no")
输出:

if (inputlist[x]) is ("r"):
    TypeError: string indices must be integers
但是,您需要执行以下操作:

inputlist = "hello world"
for x in inputlist:
    if (inputlist[x]) is ("r"):
        print("yes")
    else:
        print("no")
inputlist = "hello world"
for x in inputlist:
    if x == "r":
        print("yes")
    else:
        print("no")

你能发布完整的代码吗??什么是X????同时发布inputlist Wild guess:如果您在inputlist:
中对x执行
,则不能使用
x
索引
inputlist
。如果x==“r”,请尝试
。错误很明显。作为索引的x应该是一个整数。那么什么是x呢?谢谢你,阿比亚罗拉,你完全正确,我非常感激!伟大的很乐意帮忙。别忘了投票并接受答案。