how to check each letter in a string and do some action, in Python
<p>So I was messing around in python, and developed a problem.
I start out with a string like the following:</p>

<pre><code>a = "1523467aa252aaa98a892a8198aa818a18238aa82938a"
</code></pre>

<p>For every number, you have to add it to a <code>sum</code> variable.Also, with every encounter of a letter, the index iterator must move back 2. My program keeps crashing at <code>isinstance()</code>. This is the code I have so far: </p>

<pre><code>def sum():
    a = '93752aaa746a27a1754aa90a93aaaaa238a44a75aa08750912738a8461a8759383aa328a4a4935903a6a55503605350'
    z = 0
    for i in a:
        if isinstance(a[i], int):
            z = z + a[i]
        elif isinstance(a[i], str):
            a = a[:i] + a[(i+1):]
            i = i - 2
            continue
     print z
     return z
sum()
</code></pre>

<p>This part is not doing what you think:</p>

<pre><code>for i in a:
    if isinstance(a[i], int):
</code></pre>

<p>Since <code>i</code> is an iterator, there is no need to use <code>a[i]</code>, it will confuse Python.</p>

<p>Also, since <code>a</code> is a string, no element of it will be an <code>int</code>, they will all be <code>string</code>.  You want something like this:</p>

<pre><code>for i in a:
    if i.isdigit():
        z += int(i)
</code></pre>

<p><strong><em>EDIT:</em></strong>  removing elements of an iterable while iterating over it is a common problem on SO, I would recommend creating a new string with only the elements you wan to keep:</p>

<pre><code>z = 0
b = ''
for i in a:
    if i.isdigit():
        z += int(i)
        b += str(i)

a = b    # set a back to b so the "original string" is set to a string with all non-numeric characters removed.
</code></pre>

python string