Specifically, I have two lists of strings that I'd like to combine into a string where each line is the next two strings from the lists, separated by spaces:
a = ['foo1', 'foo2', 'foo3']
b = ['bar1', 'bar2', 'bar3']
I want a function combine_to_lines() that would return:
"""foo1 bar1
foo2 bar2
foo3 bar3"""
I admit I've already solved this problem, so I'm going to post the answer. But perhaps someone else has a better one or sees a flaw in mine.
Update: I over-simplified my example above. In my real-world problem the lines were formatted in a more complicated manner that required the tuples returned from zip() to be unpacked. But kudos to mhawke for coming up to the simplest solution to this example.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the tuple, then start at 0 and loop your way through the tuple items by refering to their indexes. Remember to increase the index by 1 after each iteration.
Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=' ' to print all items in a tuple in one line. Another print() introduces new line after each tuple.
With Python's enumerate() method you can iterate through a list or tuple while accessing both the index and value of the iterable (list or tuple) object.
We can iterate over tuples using a simple for-loop. We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.
It's not necessary to unpack and repack the tuples returned by zip:
'\n'.join(' '.join(x) for x in zip(a, b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With