如何交替排列两个字符串?



可能的重复:
一次遍历两个字符串 python

在这里,我有一个疑问,当两个字符串的单词一个接一个地出现时,如何合并两个字符串。我的意思是,例如,如果第一个字符串是"abc",第二个是"defgh",那么最终答案应该是"adbecfgh"......

这是我的代码,但它出现在同一行

x = raw_input ('Enter 1st String: ')
y = raw_input ('Enter 2st String: ')
z = [x, y]
a = ''.join(z)
print (a)

有人能知道错误吗?

如果你使用的是python 3.x,你需要在这里itertools.izip_longest()itertools.zip_longest()

In [1]: from itertools import izip_longest
In [2]: strs1="abc"
In [3]: strs2="defgh"
In [4]: "".join("".join(x) for x in izip_longest(strs1,strs2,fillvalue=""))
Out[4]: 'adbecfgh'

你想要的是itertools文档中的roundrobin()食谱:

from itertools import cycle, islice
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = cycle(iter(it).__next__ for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pending -= 1
nexts = cycle(islice(nexts, pending))

请注意 2.x 用户的细微差异。

例如:

>>> "".join(roundrobin("abc", "defgh"))
adbecfgh
x = 'abc'
y = 'defgh'
z = [x, y]
from itertools import izip_longest
print ''.join(''.join(i) for i in izip_longest(*z, fillvalue=''))

最新更新