I got the task to alternately combine the letters of two strings with the same length.
For example:
Inputstring 1: \"acegi\"
Inputstring 2: \"bdfhj\
You can do it in one line using zip and join.
out1 = ''.join(''.join(f for f in tup) for tup in zip(inp1, inp2))
or the more functional-style:
out1 = ''.join(map(''.join, zip(inp1, inp2))) # kudos @Coldspeed
which both print
abcdefghij
Braking the code down:
zip()
pairs = list(zip(inp1, inp2))
print(pairs ) # [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h'), ('i', 'j')]
.join()
temp = []
for sub in pairs:
temp.append(''.join(sub))
print(temp) # ['ab', 'cd', 'ef', 'gh', 'ij']
.join() again
out1 = ''.join(temp)
print(out1) # abcdefghij
Finally, and for your entertainment and learning only, two additional, more old-school approaches:
out1 = ''
for i in range(len(inp1)):
out1 += inp1[i] + inp2[i]
and
out1 = ''
for i, c in enumerate(inp1):
out1 += c + inp2[i]