Search code examples
pythonstringzip

How to zip 2 strings into a new string in python


I am try to figure out how to zip two strings of different length into one string alternating the chars and preserving the leftover chars in the longer string. Example:

a = '12345'
b = 'abcdefgh'

I tried zip(a,b) but it returns a list of tuples and cuts off when there aren't equal length strings:

[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd'), ('5', 'e')]

I need to get just the new string out. Example:

result = 1a2b3c4d5efgh

How can this be done?


Solution

  • One possible way: join the inner tuples and then the outer list.

    ''.join(''.join(x) for x in zip(a,b))
    

    Though, zip() will always stop aggregating when the shortest beween a and b ends (1a2b3c4d5e in your example). If you want to reach the end of the longest input string you must iterate them differently, for example:

    c = [] 
    for x in range(max(len(a),len(b))):
        c.append(a[x] if x < len(a) else '')
        c.append(b[x] if x < len(b) else '')
    result=''.join(c)
    

    Or, as suggested by Moinuddin below, using izip_longest:

    ''.join(''.join(x) for x in izip_longest(a, b, fillvalue=''))
    

    NOTE that as of Python 3, izip_longest() is now zip_longest().