将字符串转换为变量(’str‘一元+运算符的错误操作数类型)

2024-04-20 14:03:48 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我总是收到这个错误?我猜原始的输入()是作为输入()读取的,它无法将用户的输入视为字符串。我不知道怎样才能改变它,使它可以工作。不,问题是:“Python2.7获取用户输入并作为字符串进行操作而不带引号”并没有回答我的问题。你知道吗

options = ["An animal", "A food", "A fruit", "A number", "A superhero name", "A country", "A dessert", "A year"]
#"options" become variables
for i in options:
    if i[0:3] == "An ":
        exec("%s = %s" % (i[3::], raw_input("Enter " + i + " ")))
    else:
        exec("%s = %s" % (i[2::], raw_input("Enter " + i + " ")))

我一直收到这个错误:

NameError: name 'input' is not defined

Tags: 字符串用户nameannumberinputrawfood
1条回答
网友
1楼 · 发布于 2024-04-20 14:03:48

你没有提供足够的信息,但我的灵力告诉我,当提示你“输入动物”时,你键入了input。你知道吗

试着在思想上了解你的代码在做什么,特别是当你达到以下目标时:

exec("%s = %s" % (i[3::], raw_input("Enter " + i + " ")))

因此对于循环的第一次迭代,它变成:

exec("%s = %s" % ("animal", "input"))

当替换发生时:

exec("animal = input")

相当于键入:

animal = input

直接输入Python解释器。input未定义,因此您将得到:

NameError: name 'input' is not defined

您可能想用引号将右侧括起来,以便在执行时将其视为字符串:

 exec("%s = '%s'" % ("animal", "input")) # Note that this is unsafe.  See the note below.

尽管如此,我觉得有义务说这个代码非常脆弱。当循环迭代到“超级英雄名”时,它也会中断,因为superhero name不是有效的标识符。相反,您可能应该将字符串拆分为空格,或者使用第二个单词,或者用下划线替换所有空格。此外,您还需要清理用户输入,以便用户无法通过在输入中提供引号进行转义。(或者更好的办法是完全避免使用exec和用户输入。你真的需要变量名吗?为什么不使用Python字典将提示字符串映射到输入字符串?)你知道吗

相关问题 更多 >