结合两个字符串组成一个新的字符串
我正在尝试编写一个程序,要求用户输入两个字符串,并通过合并两个字符串(每次从每个字符串取一个字母)来创建一个新字符串。我不允许使用切片。如果用户输入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
我遇到的问题是,如果其中一个字符串比其他的我得到一个指标差更长。
您需要执行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
打印。
我觉得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.
肯定是比我的更好的答案,虽然可能不太符合作业的教育目标。 – Daniel
Danke Daniel!:)哎呀,我留下了她原来没有使用过的'i',谢谢你为我碰到这个。 :) –
太感谢你了! (: – Natalie