Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get character from multiple strings in sequence

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?

like image 917
Mayukh Nair Avatar asked Mar 05 '23 12:03

Mayukh Nair


1 Answers

Problems related to iterating in some convoluted order can often be solved elegantly with itertools.

Using zip

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))))

Using cycle

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))
like image 122
Olivier Melançon Avatar answered Mar 18 '23 15:03

Olivier Melançon