Python Forum
join elements from two splits
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
join elements from two splits
#1
I want to join two splitted string,

a = "a,b,c"
b = "1,2,3"

spla = a.split(",")
splb = b.split(",")
for arra, arrb in spla, splb:
  print(arra + "-" + arrb)
what I get is

Error:
Traceback (most recent call last): File "python", line 6, in <module> ValueError: too many values to unpack (expected 2)
help to get rid this.,
thank you in advance!
Reply
#2
for arra, arrb in zip(spla, splb):
    print('-'.join((arra, arrb)))
https://docs.python.org/3/library/functions.html#zip
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
spla, splb creates a two element tuple, and is the same as: (spla, splb).  Which means your for loop would iterate just twice, once for the first list, and once for the second list.  The first time, the element is ("a", "b", "c"), and the second time it'd be ("1", "2", "3").  You get that error because that's three items, and you're trying to unpack to just two variables.

zip gets around this by interleaving the iterables together, to create a single iterable of combined elements, which looks like what you were expecting the for loop to do.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  String Splits m.zod 3 5,072 Oct-05-2016, 08:14 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020