interlacing strings in python

Question:

I had a question for a test where I had to interlace letters from two strings into one, I did it using the following code:

‘abcd’ and ‘efghi’ -> ‘aebfcgdhi’

s1,s2='abcd' ,'efghi'
t=[a+b for a,b in zip(s1, s2) ]
ls1 = len(s1)
ls2 = len(s2)
if ls1 > ls2:
    t.extend(s1[ls2:])
elif ls1 < ls2:
    t.extend(s2[ls1:])
print ''.join(t)

I first tried using the following which seems to work only when strings are the same length or s2 is the longer string.

 print  ''.join([a+b for a,b in zip(s1, s2)]) + max(s1,s2)[min(len(s1),len(s2)):]

Where did I go wrong in my logic?

Asked By: Padraic Cunningham

||

Answers:

To make your code work, you just need to use the key param in the max function

print  ''.join([a+b for a,b in zip(s1, s2)]) + max(s1,s2, key=len)[min(len(s1),len(s2)):]

Alternatively, you can use itertools.izip_longest to iterate till the biggest of the two iterables is exhausted. So, this solution works irrespective of the lengths of strings.

import itertools
s1,s2='abcd' ,'efghi'
print "".join(y for x in itertools.izip_longest(s1, s2) for y in x if y)

Output

aebfcgdhi

Edit:

Without using itertools

s1,s2='abcd' ,'efghi'
minLen = min(len(s1), len(s2))
print "".join(y for x in zip(s1, s2) for y in x) + s1[minLen:] + s2[minLen:]
Answered By: thefourtheye

Without using itertools.izip_longest:

>>> s1, s2 = 'abcd', 'efghi'
>>> l = min(len(s1), len(s2))
>>> ''.join(a+b for a, b in zip(s1, s2)) + s1[l:] + s2[l:]
'aebfcgdhi'
Answered By: falsetru
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.