How to convert numbers in a string without using lists?
<p>My prof wants me to create a function that return the sum of numbers in a string but without using any lists or list methods.</p>

<p>The function should look like this when operating:</p>

<pre><code>&gt;&gt;&gt; sum_numbers('34 3 542 11')
    590
</code></pre>

<p>Usually a function like this would be easy to create when using lists and list methods. But trying to do so without using them is a nightmare.</p>

<p>I tried the following code but they don't work:</p>

<pre><code> &gt;&gt;&gt; def sum_numbers(s):
    for i in range(len(s)):
        int(i)
        total = s[i] + s[i]
        return total


&gt;&gt;&gt; sum_numbers('1 2 3')
'11'
</code></pre>

<p>Instead of getting 1, 2, and 3 all converted into integers and added together, I instead get the string '11'. In other words, the numbers in the string still have not been converted to integers.</p>

<p>I also tried using a <code>map()</code> function but I just got the same results:</p>

<pre><code>&gt;&gt;&gt; def sum_numbers(s):
    for i in range(len(s)):
        map(int, s[i])
        total = s[i] + s[i]
        return total


&gt;&gt;&gt; sum_numbers('1 2 3')
'11'
</code></pre>

<pre><code>def sum_numbers(s):
    total=0
    gt=0 #grand total
    l=len(s)
    for i in range(l):
        if(s[i]!=' '):#find each number
            total = int(s[i])+total*10
        if(s[i]==' ' or i==l-1):#adding to the grand total and also add the last number
            gt+=total
            total=0
    return gt

print(sum_numbers('1 2 3'))
</code></pre>

<p>Here each substring is converted to number and added to grant total</p>

python string python-3.x for-loop