2014-02-28 250 views
2

我正在嘗試編寫一個程序,要求用戶輸入兩個字符串,並通過合併兩個字符串(每次從每個字符串取一個字母)來創建一個新字符串。我不允許使用切片。如果用戶輸入ABCDEF和XYZW,程序應該建立字符串:axbyczdwef結合兩個字符串組成一個新的字符串

s1 = input("Enter a string: ") 
s2 = input("Enter a string: ") 
i = 0 
print("The new string is: ",end='') 
while i < len(s1): 
    print(s1[i] + s2[i],end='') 
    i += 1 

我遇到的問題是,如果其中一個字符串比其他的我得到一個指標差更長。

回答

2

您需要執行while i < min(len(s1), len(s2)),然後確保打印出字符串的其餘部分。

OR

while i < MAX(len(s1), len(s2)),然後只在你的循環s1[i]如果len(s1) > i,並只打印s2[i]如果len(s2) > i打印。

+0

太感謝你了! (: – Natalie

1

我覺得zip_longest在Python 3的itertools這裏爲您提供了最優雅的回答:

import itertools 

s1 = input("Enter a string: ") 
s2 = input("Enter a string: ") 

print("The new string is: {}".format(
     ''.join(i+j for i,j in itertools.zip_longest(s1, s2, fillvalue='')))) 

Here's the docs, with what zip_longest is doing behind the scenes.

+1

肯定是比我的更好的答案,雖然可能不太符合作業的教育目標。 – Daniel

+0

Danke Daniel!:)哎呀,我留下了她原來沒有使用過的'i',謝謝你爲我碰到這個。 :) –

相關問題