Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenate two strings elements wise

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading