Ev. Kounis Ev. Kounis - 6 months ago 21
Python Question

Impregnate string with list entries - alternating

So SO, i am trying to "merge" a string (

) and a list of strings (

a = '1234'
b = ['+', '-', '']

to get the desired output (

c = '1+2-34'

The characters in the desired output string alternate in terms of origin between string and list. Also, the list will always contain one element less than characters in the string. I was wondering what the fastest way to do this is.

what i have so far is the following:

c = a[0]
for i in range(len(b)):
c += b[i] + a[1:][i]
print(c) # prints -> 1+2-34

But i kind of feel like there is a better way to do this..


You can use itertools.zip_longest to zip the two sequences, then keep iterating even after the shorter sequence ran out of characters. If you run out of characters, you'll start getting None back, so just consume the rest of the numerical characters.

>>> from itertools import chain
>>> from itertools import zip_longest
>>> ''.join(i+j if j else i for i,j in zip_longest(a,b))

As @deceze suggested in the comments, you can also pass a fillvalue argument to zip_longest which will insert empty strings. I'd suggest his method since it's a bit more readable.

>>> ''.join(i+j for i,j in zip_longest(a,b, fillvalue=''))

A further optimization suggested by @ShadowRanger is to remove the temporary string concatenations (i+j) and replace those with an itertools.chain.from_iterable call instead

>>> ''.join(chain.from_iterable(zip_longest(a, b, fillvalue='')))