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>You could write a generator:</p>

<pre><code>def nums(s):
    idx=0
    while idx&lt;len(s):
        ns=''
        while idx&lt;len(s) and s[idx].isdigit():
            ns+=s[idx]
            idx+=1
        yield int(ns)
        while idx&lt;len(s) and not s[idx].isdigit():
            idx+=1

&gt;&gt;&gt; list(nums('34 3 542 11'))
[34, 3, 542, 11]
</code></pre>

<p>Then just sum that:</p>

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

<p>or, you could use <code>re.finditer</code> with a regular expression and a generator construction:</p>

<pre><code>&gt;&gt;&gt; sum(int(m.group(1)) for m in re.finditer(r'(\d+)', '34 3 542 11'))
590
</code></pre>

<p>No lists used...</p>

python string python-3.x for-loop