【问题标题】:Designating a Boolean as true from a raw_input string?从 raw_input 字符串中将布尔值指定为真?
【发布时间】:2015-07-26 00:36:29
【问题描述】:

我有一个简单的 if elif else 语句,它依赖于用户的输入。

options = ['Try to jump the gap', 'Go back to the entryway']
print "You can:"
for x in options:
    print "\t:>%s" % x
choice = raw_input("What do you do?")
if  'try' in choice:
    print "You try to jump the gap and fail."
    print "You fall into the pool of acid while shrieking in pain."
    print "You dissolve"
    dead()
elif 'go' in choice:
    change()
    entrywaymain()
else:
    unknown()
    change()
    poolroomclosed()

当用户只输入“try”或“go”时,该代码有效。 但是,如果用户输入完整的语句,无论是“尝试跳过间隙”还是“回到入口通道”,他们总是会得到 if 值并且会死。那么,我如何编码才能激活布尔值用户输入中只有该字符串中的单词。

【问题讨论】:

  • 可能是choice.lower() == 'try'choice.lower().startswith('try')

标签: python if-statement boolean


【解决方案1】:

这可能是因为“Go back to the entryway”包含“try”。

目前,由于这个原因,简单地使用if "try" in choice: 很容易出错。您最好使用其他人提到的方法检查字符串的开头:

choice.split()[0].lower() == "try"
# Returns True for "try to jump" but not for "tryto jump"

choice.split(" ")[0].lower() == "try"
# Equivalent to the above

choice.lower().startswith("try")
# Returns True for "try to jump" and "tryto jump"

(大小写对于这些 sn-ps 中的任何一个都无关紧要。)

【讨论】:

    【解决方案2】:

    如果你想得到choice的第一个单词,你可以这样做:

    choice.split(' ')[0]
    

    也可以小写:

    choice.split(' ')[0].lower()
    

    编辑: jweyrich 的解决方案似乎更优雅(我不知道有一个startwith 字符串方法),我只是将他的解决方案修改为choice.lower().startswith('try'),所以它适用于您的示例(Python 字符串区分大小写)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2017-10-25
      • 2022-07-31
      相关资源
      最近更新 更多