Impregnate string with list entries - alternating
<p>So SO, i am trying to "merge" a string (<code>a</code>) and a list of strings (<code>b</code>):</p>

<pre><code>a = '1234'
b = ['+', '-', '']
</code></pre>

<p>to get the desired output (<code>c</code>):</p>

<pre><code>c = '1+2-34'
</code></pre>

<p>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. </p>

<p>what i have so far is the following:</p>

<pre><code>c = a[0]
for i in range(len(b)):
    c += b[i] + a[1:][i]
print(c)  # prints -&gt; 1+2-34
</code></pre>

<p>But i kind of feel like there is a better way to do this..</p>

<p>You can use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>itertools.zip_longest</code></a> to <code>zip</code> 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 <code>None</code> back, so just consume the rest of the numerical characters.</p>

<pre><code>&gt;&gt;&gt; from itertools import chain
&gt;&gt;&gt; from itertools import zip_longest
&gt;&gt;&gt; ''.join(i+j if j else i for i,j in zip_longest(a, b))
'1+2-34'
</code></pre>

<p>As <a href="https://stackoverflow.com/users/476/deceze">@deceze</a> suggested in the comments, you can also pass a <code>fillvalue</code> argument to <code>zip_longest</code> which will insert empty strings. I'd suggest his method since it's a bit more readable.</p>

<pre><code>&gt;&gt;&gt; ''.join(i+j for i,j in zip_longest(a, b, fillvalue=''))
'1+2-34'
</code></pre>

<p>A further optimization suggested by <a href="https://stackoverflow.com/users/364696/shadowranger">@ShadowRanger</a> is to remove the temporary string concatenations (<code>i+j</code>) and replace those with an <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a> call instead</p>

<pre><code>&gt;&gt;&gt; ''.join(chain.from_iterable(zip_longest(a, b, fillvalue='')))
'1+2-34'
</code></pre>

python