How do I take the first character from each string in a list, join them together, then the second character from each string, join them together, and so on - and eventually create one combined string?
eg. if I have strings like these:
homanif
eiesdnt
ltiwege
lsworar
I want the end result to be helloitsmeiwaswonderingafter
I put together a very hackneyed version of this which does the job but produces an extra line of gibberish. Considering this is prone to index going out of range, I don't think this is a good approach:
final_c = ['homanif', 'eiesdnt', 'ltiwege', 'lsworar']
final_message = ""
current_char = 0
for i in range(len(final_c[1])):
for c in final_c:
final_message += c[current_char]
current_char += 1
final_message += final_c[0][:-1]
print(final_message)
gives me helloitsmeiwaswonderingafterhomani
when it should simply stop at helloitsmeiwaswonderingafter
.
How do I improve this?
Problems related to iterating in some convoluted order can often be solved elegantly with itertools
.
You can use zip
and itertools.chain
together.
from itertools import chain
final_c = ['homanif', 'eiesdnt', 'ltiwege', 'lsworar']
final_message = ''.join(chain.from_iterable(zip(*final_c))) # 'helloitsmeiwaswonderingafter'
In the event you needed the strings in final_c
to be of different lengths, you could tweak your code a bit by using itertools.zip_longest
.
final_message = ''.join(filter(None, chain.from_iterable(zip_longest(*final_c))))
The fun part with itertools
is that it offers plenty of clever short solutions for iterating over objects. Here is another using itertools.cycle
.
from itertools import cycle
final_c = ['homanif', 'eiesdnt', 'ltiwege', 'lsworara']
final_message = ''.join(next(w) for w in cycle(iter(w) for w in final_c))
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