如何在Python中交错字符串?

nar*_*esh 7 python

如何在Python中交错字符串?

特定

s1 = 'abc'
s2 = 'xyz'
Run Code Online (Sandbox Code Playgroud)

我怎么得到axbycz

Joh*_*ooy 15

这是一种方法

>>> s1 = "abc"
>>> s2 = "xyz"
>>> "".join(i for j in zip(s1, s2) for i in j)
'axbycz'
Run Code Online (Sandbox Code Playgroud)

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

>>> s3 = "123"
>>> "".join(i for j in zip(s1, s2, s3) for i in j)
'ax1by2cz3'
Run Code Online (Sandbox Code Playgroud)

这是另一种方式

>>> "".join("".join(i) for i in zip(s1,s2,s3))
'ax1by2cz3'
Run Code Online (Sandbox Code Playgroud)

而另一个

>>> from itertools import chain
>>> "".join(chain(*zip(s1, s2, s3)))
'ax1by2cz3'
Run Code Online (Sandbox Code Playgroud)

一个没有 zip

>>> b = bytearray(6)
>>> b[::2] = "abc"
>>> b[1::2] = "xyz"
>>> str(b)
'axbycz'
Run Code Online (Sandbox Code Playgroud)

而且效率低下

>>> ((s1 + " " + s2) * len(s1))[::len(s1) + 1]
'axbycz'
Run Code Online (Sandbox Code Playgroud)

  • 选择什么?哪一个是"最好只有一种明显的方法"? (2认同)