brad
brad

Reputation: 11

Adding the characters of two strings together

def merge(string1, string2):        
    print( "".join(i for j in zip(string1, string2) for i in j))

When I run merge("big","small") the output is bsimga, I want the code to output bsimgall.

How can I add the characters from both strings in an alternating fashion even if the strings are not the same length?

Upvotes: 1

Views: 62

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123260

zip() will only produce pairs until the shortest iterable is exhausted. Use itertool.zip_longest() to iterate onwards and use a fill value to pad out the shorter string. Use an empty string to pad:

from itertools import zip_longest

def merge(string1, string2):        
    print("".join(i for j in zip_longest(string1, string2, fillvalue='') for i in j))

You can leave the joining to print():

def merge(string1, string2):        
    print(*(i for j in zip_longest(string1, string2, fillvalue='') for i in j), sep='')

and you can use itertools.chain.from_iterable() to flatten the result:

from itertools import chain, zip_longest

def merge(string1, string2):        
    print(*chain.from_iterable(zip_longest(string1, string2, fillvalue='')), sep='')

Upvotes: 2

Related Questions