Repeating characters results in wrong repetition counts
<p>My function looks like this:</p>

<pre><code>def accum(s):
    a = []
    for i in s:
        b = s.index(i)
        a.append(i * (b+1))
    x = "-".join(a)
    return x.title()
</code></pre>

<p>with the expected input of:</p>

<pre><code>'abcd'
</code></pre>

<p>the output should be and is:</p>

<pre><code>'A-Bb-Ccc-Dddd' 
</code></pre>

<p>but if the input has a recurring character:</p>

<pre><code>'abccba'
</code></pre>

<p>it returns:</p>

<pre><code>'A-Bb-Ccc-Ccc-Bb-A'
</code></pre>

<p>instead of:</p>

<pre><code>'A-Bb-Ccc-Cccc-Bbbbb-Aaaaaa'
</code></pre>

<p>how can I fix this?</p>

<p>Don't use <code>str.index()</code>, it'll return the <em>first match</em>. Since <code>c</code> and <code>b</code> and a appear early in the string you get <code>2</code>, <code>1</code> and <code>0</code> back regardless of the position of the <em>current</em> letter.</p>

<p>Use the <a href="https://docs.python.org/3/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code> function</a> to give you position counter instead:</p>

<pre><code>for i, letter in enumerate(s, 1):
    a.append(i * letter)
</code></pre>

<p>The second argument is the starting value; setting this to 1 means you can avoid having to <code>+ 1</code> later on. See <a href="https://stackoverflow.com/questions/22171558/what-does-enumerate-mean">What does enumerate mean?</a> if you need more details on what <code>enumerate()</code> does.</p>

<p>You can use a list comprehension here rather than use <code>list.append()</code> calls:</p>

<pre><code>def accum(s):
    a = [i * letter for i, letter in enumerate(s, 1)]
    x = "-".join(a)
    return x.title()
</code></pre>

<p>which could, at a pinch, be turned into a one-liner:</p>

<pre><code>def accum(s):
    a = '-'.join([i * c for i, c in enumerate(s, 1)]).title()
</code></pre>

python