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>

<p>No lists were used (nor harmed) in the production of this answer:</p>

<pre><code>def sum_string(string):
    total = 0

    if len(string):
        j = string.find(" ") % len(string) + 1
        total += int(string[:j]) + sum_string(string[j:])

    return total
</code></pre>

<p>If the string is noisier than the OP indicates, then this should be more robust:</p>

<pre><code>import re

def sum_string(string):
    pattern = re.compile(r"[-+]?\d+")

    total = 0

    match = pattern.search(string)

    while match:

        total += int(match.group())

        match = pattern.search(string, match.end())

    return total
</code></pre>

<p><strong>EXAMPLES</strong></p>

<pre><code>&gt;&gt;&gt; sum_string('34 3 542 11')
590
&gt;&gt;&gt; sum_string('   34    4   ')
38
&gt;&gt;&gt; sum_string('lksdjfa34adslkfja4adklfja')
38
&gt;&gt;&gt; # and I threw in signs for fun
... 
&gt;&gt;&gt; sum_string('34 -2 45 -8 13')
82
&gt;&gt;&gt; 
</code></pre>

python string python-3.x for-loop