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've definitely put some effort in here, but one part of your approach definitely won't work as-is: you're iterating over the <em>characters</em> in the string, but you keep trying to treat each character as its own number. I've written a (very commented) method that accomplishes what you want without using any lists or list methods:</p>

<pre><code>def sum_numbers(s):
    """
    Convert a string of numbers into a sum of those numbers.

    :param s: A string of numbers, e.g. '1 -2 3.3 4e10'.
    :return: The floating-point sum of the numbers in the string.
    """
    def convert_s_to_val(s):
        """
        Convert a string into a number. Will handle anything that
        Python could convert to a float.

        :param s: A number as a string, e.g. '123' or '8.3e-18'.
        :return: The float value of the string.
        """
        if s:
            return float(s)
        else:
            return 0
    # These will serve as placeholders.
    sum = 0
    current = ''
    # Iterate over the string character by character.
    for c in s:
        # If the character is a space, we convert the current `current`
        # into its numeric representation.
        if c.isspace():
            sum += convert_s_to_val(current)
            current = ''
        # For anything else, we accumulate into `current`.
        else:
            current = current + c
    # Add `current`'s last value to the sum and return.
    sum += convert_s_to_val(current)
    return sum
</code></pre>

<hr>

<p>Personally, I would use this one-liner, but it uses <code>str.split()</code>:</p>

<pre><code>def sum_numbers(s):
    return sum(map(float, s.split()))
</code></pre>

python string python-3.x for-loop