views:

130

answers:

2

How do I interleave strings in Python?

Given

s1 = 'abc'
s2 = 'xyz'

How do I get axbycz?

A: 

Have you tried reading the fine manual? It really helps!

badp
[Original question](http://stackoverflow.com/revisions/05d61c84-64d0-4fdb-8f4f-9866b7deb2d9/view-source)
badp
OK as a comment, not a very good answer though.
MJB
+4  A: 

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'
gnibbler