").split(" ") I want ...">

Get user input and save it up to three variables

I have a problem with the following code:

cmd, arg, arg1 = input("> ").split(" ")

I want to get input to these three vars. But if I leave argit arg1blank, Python complains:

Not enough values ​​to unpack (expected 3, received 1)

How can i avoid this?

I want to do argand arg1optional.

+4
source share
2 answers

you cannot decompress into variables if the size changes. Well, not like that.

You can, using advanced iterative unpacking (also known as unpacking stars) (Python 3 only):

cmd, *args = input("> ").split(" ")

, , args , , .

if not args:
  # there are no arguments
  pass
elif len(args)>2:
  print("too many args")
else:
  print("args",args)

, split(" ") . split() ( : , ), shlex.split(input("> "))

: python 2 . , .

+7

:

inp=input("> ").split(" ")
l = len(inp)
if l >= 1:
    cmd = inp[0]
if l >= 2:
    arg1 = inp[1]
if l >= 3:
    arg2 = inp[2]
+2

Source: https://habr.com/ru/post/1683844/


All Articles