I came across a problem in which i had to concatenate two string element wise for ex :
str1 = "ABCD"
str2 = "EFGH"
output = "AEBFCGDH"
I wrote this code
op = ''
op = op.join([i j for i, j in zip(str1, str2)])
print(op)
And it worked but I was wondering if the length of two strings is different for ex:
str1 = "ABC"
str2 = "DEFGH"
output = "ADBECFGH"
or
str1 = "ABCDG"
str2 = "DEF"
output = "ADBECFDG"
How do I code for this ?
CodePudding user response:
Just switch zip()
with zip_longest()
:
from itertools import zip_longest
str1 = "ABCDG"
str2 = "DEF"
output = ''.join([i j for i, j in zip_longest(str1, str2, fillvalue="")])
print(output) # ADBECFDG
CodePudding user response:
You could take the shorter string, zip until its length and then concatenate the remaining part of the longer string. eg:
str1 = 'ABC'
str2 = 'DEFGH'
op = ''
if len(str1)>len(str2):
op = op.join([i j for i, j in zip(str1, str2)]) str1[len(str2):]
else:
op = op.join([i j for i, j in zip(str1, str2)]) str2[len(str1):]
print(op) # output: ADBECFGH
zip() only zips until the shorter of the two iterables. See: https://docs.python.org/3.3/library/functions.html#zip
CodePudding user response:
Simple solution:
str1 = "ABCDG"
str2 = "DEF"
suffix_start = min(len(str1), len(str2))
suffix = str1[suffix_start:] str2[suffix_start:]
output = ''.join([i j for i, j in zip(str1, str2)]) suffix
print(output) # ADBECFDG