Python string.split more than one value in for loop
Solution 1
Split on "=" gives you two values:
"x", "y"
The fact that those values match your variable names is incidental. You could also do:
x,xx = "x=y".split("=")
I suspect what you are likely planning is to take a list:
"foo=bar,blah=boo,etc=something"
And split it, for which you could do:
for x,y in [ (pair.split("=")) for pair in "foo=bar,blah=boo,etc=something".split(",") ]:
print x,y
BUT! While it works, I think it would be much better to split it into individual steps as it's much more readable:
params = "foo=bar,blah=boo,etc=something"
pair_list = params.split(",")
for pair in pair_list:
x,y = pair.split("=")
...
Solution 2
You could do
for x in "x=y".split("="):
# ...
What you tried is to iterate over the sequence ["x", "y"]
, but assign to x, y
for each entry of the sequence. That would be equivalent to
x, y = "x"
for the first iteration, which does not make any sense.
Solution 3
I'm not sure why you would ever want to do this, but if for some reason you would like to use a for
loop for this:
>>> for x, y in ["x=y".split("=")]:
... print x
... print y
...
x
y
mcot
Updated on July 09, 2022Comments
-
mcot almost 2 years
Basically this works 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 could fix this for loop.
-
mcot about 13 yearsHumm.. but I want to assign to "x". Any way to do this without the extra step of saying, x = x[0] inside the for loop?
-
Admin about 13 years@user: Using
for x in ...
,x
is the first item of the listsplit
returns (on the first iteration, on the second it's the second item, i.e."y"
). -
mcot about 13 yearsYep, this is exactly what I intended to do, thanks for the answer.
-
Admin about 13 yearsNot cramming the list comprehension into the loop header is a good idea. Moving the tuple unpacking into the loop and introducing a bogus variable
pair
is not - just usefor x, y in pair_list
(ideally,x
andy
would get more meaningful names as well...). -
Ofer about 13 years@delnan, pair_list looks like ["foo=bar", "blah=boo", "etc=something"], it's not a list of tuples, but a list of strings. There are probably faster ways to process the whole string, but I think it would be a premature optimization. Am I missing something?
-
Admin about 13 yearsNo, I somehow thought the pairs were already split (well, I would have suggested
pair_list = [raw_pair.split('=') for raw_pair in params.split(',')]
). -
Ofer about 13 years@delnan, no problem. BTW, that's effectively the first example I gave, but without assignment to a variable.