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>If we omit the fact <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow"><code>eval</code></a> is <a href="http://stackoverflow.com/questions/1832940/is-using-eval-in-python-a-bad-practice">evil</a>, we can solve that problem with it.</p>

<pre><code>def sum_numbers(s):
    s = s.replace(' ', '+')
    return eval(s)
</code></pre>

<p>Yes, that simple. But i won't put that thing in production.</p>

<p>And sure we need to test that:</p>

<pre><code>from hypothesis import given
import hypothesis.strategies as st


@given(list_num=st.lists(st.integers(), min_size=1))
def test_that_thing(list_num):
    assert sum_numbers(' '.join(str(i) for i in list_num)) == sum(list_num)

test_that_thing()
</code></pre>

<p>And it would raise nothing.</p>

python string python-3.x for-loop