Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interleave strings in Python? [closed]

Tags:

python

How do I interleave strings in Python?

Given

s1 = 'abc'
s2 = 'xyz'

How do I get axbycz?

like image 325
naresh Avatar asked Jun 21 '10 10:06

naresh


2 Answers

Here is one way to do it

>>> s1 = "abc"
>>> s2 = "xyz"
>>> "".join(i for j in zip(s1, s2) for i in j)
'axbycz'

It also works for more than 2 strings

>>> s3 = "123"
>>> "".join(i for j in zip(s1, s2, s3) for i in j)
'ax1by2cz3'

Here is another way

>>> "".join("".join(i) for i in zip(s1,s2,s3))
'ax1by2cz3'

And another

>>> from itertools import chain
>>> "".join(chain(*zip(s1, s2, s3)))
'ax1by2cz3'

And one without zip

>>> b = bytearray(6)
>>> b[::2] = "abc"
>>> b[1::2] = "xyz"
>>> str(b)
'axbycz'

And an inefficient one

>>> ((s1 + " " + s2) * len(s1))[::len(s1) + 1]
'axbycz'
like image 53
John La Rooy Avatar answered Oct 03 '22 18:10

John La Rooy


What about (if the strings are the same length):

s1='abc'
s2='xyz'
s3=''
for x in range(len(s1)):
   s3 += '%s%s'%(s1[x],s2[x])

I'd also like to note that THIS article is now the #1 Google search result for "python interleave strings," which given the above comments I find ironic :-)

like image 42
mossmatters Avatar answered Oct 03 '22 18:10

mossmatters