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

时间:2012-11-03 11:58:37

标签: python

  

可能重复:
  Traversing two strings at a time python

在这里,我有一个问题是如何连接两个字符串,因为它们的单词一个接一个地出现。我的意思是作为例如如果第一个strinng是“abc”而第二个是“defgh”那么最后的答案应该是“adbecfgh”......

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

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

有人知道这个错误吗?

3 个答案:

答案 0 :(得分:6)

如果您使用的是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'

答案 1 :(得分:3)

您想要的是来自the itertools docsroundrobin()食谱:

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

注意the slight differences for 2.x users

例如:

>>> "".join(roundrobin("abc", "defgh"))
adbecfgh

答案 2 :(得分:0)

x = 'abc'
y = 'defgh'
z = [x, y]

from itertools import izip_longest
print ''.join(''.join(i) for i in izip_longest(*z, fillvalue=''))