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>You have a few problems with your code. You don't seem to understand how <code>for... in</code> loops work, but @Will already addressed that problem in his answer. Furthermore, you have a misunderstanding of how <code>isinstance()</code> works. As the numbers are characters of a string, when you iterate over that string each character will also be a (one-length) string. <code>isinstance(a[i], int)</code> will fail for every character regardless of whether or not it can be converted to an <code>int</code>. What you actually want to do is just try converting each character to an <code>int</code> and adding it to the total. If it works, great, and if not just catch the exception and keep on going. You don't need to worry about non-numeric characters because when each one raises a <code>ValueError</code> it will simply be ignored and the next character in the string will be processed.</p>

<pre><code>string = '93752aaa746a27a1754aa90a93aaaaa238a44a75aa08750912738a8461a8759383aa328a4a4935903a6a55503605350'

def sum_(string):
    total = 0
    for c in string:
        try:
            total += int(c)
        except ValueError:
            pass
     return total

sum_(string)
</code></pre>

<p>Furthermore, this function is equivalent to the following one-liners:</p>

<pre><code>sum(int(c) for c in string if c.isdigit())
</code></pre>

<p>Or the functional style...</p>

<pre><code>sum(map(int, filter(str.isdigit, string)))
</code></pre>

python string