String1 = "abcd"
String2 = "uvwxyz"
I want it to merge to look like this: aubvcwdxyz
String1 = "abcd"
String2 = "uvwxyz"
I want it to merge to look like this: aubvcwdxyz
You can use 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)
Output
aubvcwdxyz
Here's a version that works with Python 2. Spot the difference!
from itertools import izip_longest
s1 = "abcd"
s2 = "uvwxyz"
s3 = ''.join(a + b for a, b in izip_longest(s1, s2, fillvalue=''))
print(s3)
If you want to use 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]
What about iteration_utilities.roundrobin
:
>>> from iteration_utilities import roundrobin
>>> ''.join(roundrobin(String1, String2))
'aubvcwdxyz'
1 This is from a third-party library I have written: iteration_utilities
.