如何在"双输入输入中允许单个输入"?

时间:2016-10-24 22:27:36

标签: python

所以,我有这个代码允许两个输入:

if S:   # check if S is not empty
    print "list is not empty"  # S is list, not string
else:
    print "list is empty"

"颜色2" /"颜色3"事情有效。但是,键入" hello",就像它一样 一个单词,给我这个错误:

a, b = input("Enter a command: ").split()
if(a == 'hello'):
    print("Hi")
elif(a == 'color' and b == '3'):
    print("Changing color to 3")
    #example, doesn't actually change color
elif(a == 'color' and b == '2'):
    print("Changing color to 2")
else:
    print("invalid command")

那么,我该如何解决/解决这个问题呢? 我希望这个格式正确和一切,谢谢你花时间看看这个问题。我对python很陌生,很抱歉,如果这是一个简单的解决方法。

1 个答案:

答案 0 :(得分:5)

如果您事先不知道该命令有多少个参数,那么您就不能使用这个结构:

a, b = input("Enter a command: ").split()

您可以尝试这样:

a, _, b = input("Enter a command: ").partition(' ')

或者,我可以建议使用更详细的变量名称:

command, separator, arguments = input("Enter a command: ").partition(' ')

在第一个'命令之后,它将适用于任意数量的参数。单词,因为str.partition保证返回3元组。