>> print x x But this giv...">

Python string.split more than one value for for loop

This basically works just fine:

>>> x,y = "x=y".split("=")
>>> print x
x

But this gives an error:

>>> for x, y in "x=y".split("="):
...     print x
...

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I am wondering what the difference is and how I can fix this for a loop.

+3
source share
4 answers

Divide by "=" gives two values:

"x", "y"

The fact that these values ​​match your variable names is random. You can also do:

x,xx = "x=y".split("=")

I suspect you are probably planning on taking a list:

"foo=bar,blah=boo,etc=something"

And split it up, for which you can do:

for x,y in [ (pair.split("=")) for pair in "foo=bar,blah=boo,etc=something".split(",") ]:
    print x,y

BUT! Although it works, I think it would be much better to break it into separate steps, since it will be more readable:

params = "foo=bar,blah=boo,etc=something"
pair_list = params.split(",")
for pair in pair_list:
    x,y = pair.split("=")
    ...
+9
source

You could do

for x in "x=y".split("="):
    # ...

, , ["x", "y"], x, y .

 x, y = "x"

, .

+2

, - , - for :

>>> for x, y in ["x=y".split("=")]:
...   print x
...   print y
... 
x
y
+1

split . for . : 'k=y'.split('=') , ['k', 'y']. for, "k", "y".

, for, , for .

, for . : [('x', 'y'), ...]

0

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


All Articles