我需要找到一种方法以某种顺序合并python中的2个字符串?

时间:2017-01-26 23:33:03

标签: python string

String1 = "abcd"
String2 = "uvwxyz"

我希望它合并为:aubvcwdxyz

3 个答案:

答案 0 :(得分:1)

您可以使用itertools.zip_longest

from itertools import zip_longest

s1 = "abcd"
s2 = "uvwxyz"
s3 = ''.join(a + b for a, b in zip_longest(s1, s2, fillvalue=''))
print(s3)

<强>输出

aubvcwdxyz

这是一个适用于Python 2的版本。发现差异!

from itertools import izip_longest

s1 = "abcd"
s2 = "uvwxyz"
s3 = ''.join(a + b for a, b in izip_longest(s1, s2, fillvalue=''))
print(s3)

答案 1 :(得分:1)

如果你想使用python 2:

a = list("abcd")
b = list("uvwxyz")
q = list(map(None, a, b))
output = ""
for i in q:
    if i[0] is not None:
        output+=i[0]
    if i[1] is not None:
        output+=i[1]

答案 2 :(得分:0)

iteration_utilities.roundrobin

怎么样?
>>> from iteration_utilities import roundrobin

>>> ''.join(roundrobin(String1, String2))
'aubvcwdxyz'

1这来自我写的第三方库:iteration_utilities