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 ?
>Solution :
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