如何在Python中交错字符串?

时间:2023-01-25 07:12:41

How do I interleave strings in Python?

如何在Python中交错字符串?

Given

s1 = 'abc'
s2 = 'xyz'

How do I get axbycz?

我如何获得axbycz?

3 个解决方案

#1


14  

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

它也适用于超过2个字符串

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

#2


1  

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 :-)

我还要注意,这篇文章现在是“python interleave strings”的#1谷歌搜索结果,给出了上述评论我觉得讽刺:-)

#3


0  

A mathematical one, 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 another one:

还有一个:

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

#1


14  

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

它也适用于超过2个字符串

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

#2


1  

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 :-)

我还要注意,这篇文章现在是“python interleave strings”的#1谷歌搜索结果,给出了上述评论我觉得讽刺:-)

#3


0  

A mathematical one, 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 another one:

还有一个:

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