How to alternate strings in Python?

How to alternate strings in Python?

Considering

s1 = 'abc' s2 = 'xyz' 

How do i get axbycz ?

+5
source share
3 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 lines

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

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

 >>> ((s1 + " " + s2) * len(s1))[::len(s1) + 1] 'axbycz' 
+14
source

How 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 would also like to point out that this article is now the result of a Google # 1 search for โ€œpython striping stringsโ€ which, given the comments above, I find ironic :-)

+1
source

Math, for fun

 s1="abc" s2="xyz" lgth = len(s1) ss = s1+s2 print ''.join(ss[i//2 + (i%2)*lgth] for i in xrange(2*lgth)) 

And one more:

 s1="abc" s2="xyz" lgth = len(s1) tu = (s1,s2) print ''.join(tu[i%2][i//2] for i in xrange(2*lgth)) # or print ''.join((tu[0] if i%2==0 else tu[1])[i//2] for i in xrange(2*lgth)) 
0
source

All Articles