如何在不使用列表的情况下转换字符串中的数字?

Mou*_*yer 5 python string for-loop python-3.x

我的教授希望我创建一个函数,该函数返回字符串中的数字总和但不使用任何列表或列表方法.

操作时该功能应如下所示:

>>> sum_numbers('34 3 542 11')
    590
Run Code Online (Sandbox Code Playgroud)

通常,使用列表和列表方法时,很容易创建这样的函数.但试图在不使用它们的情况下这样做是一场噩梦.

我尝试了以下代码,但它们不起作用:

 >>> def sum_numbers(s):
    for i in range(len(s)):
        int(i)
        total = s[i] + s[i]
        return total


>>> sum_numbers('1 2 3')
'11'
Run Code Online (Sandbox Code Playgroud)

不是将1,2和3全部转换为整数并加在一起,而是将字符串设为'11'.换句话说,字符串中的数字仍未转换为整数.

我也试过使用一个map()函数,但我得到了相同的结果:

>>> def sum_numbers(s):
    for i in range(len(s)):
        map(int, s[i])
        total = s[i] + s[i]
        return total


>>> sum_numbers('1 2 3')
'11'
Run Code Online (Sandbox Code Playgroud)

Jac*_*ijm 6

完全是愚蠢的,但为了好玩:

s = '34 3 542 11'

n = ""; total = 0
for c in s:
    if c == " ":
        total = total + int(n)
        n = ""
    else:
        n = n + c
# add the last number
total = total + int(n)

print(total)
> 590
Run Code Online (Sandbox Code Playgroud)

这假设所有字符(除了空格)都是数字.