Alternatively replace chars in the string with the corresponding index
<p>How to replace the alternative characters in the string with the corresponding index without iterating? For example:</p>

<pre><code>'abcdefghijklmnopqrstuvwxyz'
</code></pre>

<p>should be returned as:</p>

<pre><code>'a1c3e5g7i9k11m13o15q17s19u21w23y25'
</code></pre>

<p>I have the below code to achieve this. <em>But is there a way to skip the loop or, more pythonic way to achieve this</em>:</p>

<pre><code>string = 'abcdefghijklmnopqrstuvwxyz'
new_string = ''
for i, c in enumerate(string):
    if i % 2:
        new_string += str(i)
    else:
        new_string += c
</code></pre>

<p>where <code>new_string</code> hold my required value</p>

<p>You could use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>, and re-join the characters with <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>; the latter avoids repeated (slow) string concatenation):</p>

<pre><code>newstring = ''.join([str(i) if i % 2 else l for i, l in enumerate(string)])
</code></pre>

<p>Note that you can't evade iteration here. Even if you defined a large list of pre-stringified odd numbers here (<code>odds = [str(i) for i in range(1, 1000, 2)]</code>) then re-use that to use slice assignment on a list <code>string_list[1::2] = odds[:len(string) // 2]</code> Python has to iterate under the hood to re-assign the indices. That's the nature of working with an arbitrary-length sequence.</p>

python string list-comprehension