2012-11-03 30 views
1

可能重複:
Traversing two strings at a time python如何排列兩個字符串?

這裏我有疑問,怎麼concate兩個字符串作爲他們的話是接連出現。我的意思是作爲例如如果第一個strinng是「ABC」和第二個是「defgh」,那麼最終的答案應該是「adbecfgh」 ......

這裏是我的代碼,但它出現在同一行

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

燦有誰知道錯誤?

+0

還有正好問的第一頁上的問題一樣的東西! – SilentGhost

+0

@SilentGhost:請注意,不僅問題是重複的,但一些答案也幾乎是精確的複製粘貼副本。我在這些'活動'中看不到任何意義。 – georg

回答

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 
+0

這並不會將字符串置於所需的順序 –

+0

@JakobBowyer事實上,誤讀了問題,並進行了更新。 –

+0

:)好的回答+1 –

6

你需要在這裏itertools.izip_longest()itertools.zip_longest()如果您對Python 3.x都有:

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

需要注意的是,它在3.x中被重命名爲''zip_longest()'',但是對於一個簡單的答案,它被重命名爲''zip_longest()''。 –

+0

Yeap它的工作:)但是有沒有其他簡單的方法來做到這一點?我的意思是使用簡單的變量,如計數器和長度和所有..? –

+0

@NishaKothari看到我的其他解決方案[這裏](http://stackoverflow.com/a/13208159/846892),但我想zip_longest()很簡單,並接受這個答案,如果它適合你。 –

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

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