gpt4 book ai didi

python - 如何在 "two-input input"中允许单个输入?

转载 作者:太空宇宙 更新时间:2023-11-04 08:46:17 26 4
gpt4 key购买 nike

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

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")

并且“颜色 2”/“颜色 3”有效。然而,输入“你好”,因为它是一个词,给我这个错误:

ValueError: not enough values to unpack (expected 2, got 1)

那么,我该如何解决/解决这个问题?我希望这是正确的格式和一切,感谢您花时间看问题。我是 python 的新手,很抱歉,如果这是一个简单的修复。

最佳答案

如果您事先不知道命令有多少个参数,则不能使用此结构:

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 元组。

关于python - 如何在 "two-input input"中允许单个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40228565/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com