Python 尝试在输入中使用3个以上的值时发生ValueError
所以,如果我想接受由空格分隔的用户的输入,我会使用以下代码:Python 尝试在输入中使用3个以上的值时发生ValueError,python,python-3.x,Python,Python 3.x,所以,如果我想接受由空格分隔的用户的输入,我会使用以下代码: x, _, x2 = input("> ").lower().partition(' ') 这很好用。但是,如果我想接受3个响应,那么我会得到一个ValueError: x, _, x2, _, x3 = input("> ").lower().partition(' ') ValueError: not enough values to unpack (expected 5, got 3) 因此,如何使用此方法或其他
x, _, x2 = input("> ").lower().partition(' ')
这很好用。但是,如果我想接受3个响应,那么我会得到一个ValueError:
x, _, x2, _, x3 = input("> ").lower().partition(' ')
ValueError: not enough values to unpack (expected 5, got 3)
因此,如何使用此方法或其他方法接受两个以上的输入?分区方法始终只返回3个值:
S.partition(sep) -> (head, sep, tail)
Search for the separator sep in S, and return the part before it,
the separator itself, and the part after it. If the separator is not
found, return S and two empty strings.
你可能想要分开
或更灵活地:
xs = input("> ").lower().split(' ')
或者一次性:
x1, x2, x3 = (input("> ").lower().split(' ') + [None, None, None])[0:3]
这是可行的,但我想允许人们输入少于3个,这样他们就可以做一些类似foo或foo-bar的事情,而不必总是写三件事。对于像copy这样需要3个答案的命令,但是像rename这样的命令只需要2@Brendan然后分配给列表或使用上述第三种方法。
x1, x2, x3 = (input("> ").lower().split(' ') + [None, None, None])[0:3]