So SO, i am trying to "merge" a string (
a = '1234'
b = ['+', '-', '']
c = '1+2-34'
c = a
for i in range(len(b)):
c += b[i] + a[1:][i]
print(c) # prints -> 1+2-34
You can use
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)) '1+2-34'
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='')) '1+2-34'
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=''))) '1+2-34'