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.
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("=")
...