如何将数字 和 与字符串分开并返回它们的总和?

Jak*_*ake 1 python integer for-loop

我得到一个字符串,它loop_str="a1B2c4D4e6f1g0h2I3"必须编写一个代码,将“loop_str”中包含的所有数字相加,然后在最后打印出总和。总和预计将保存在名为“total”的变量下。我上面写的代码虽然达到了正确的答案,但我仍在努力定义总计并为这个特定任务创建一个 for 循环。

sum_digits = [int(x) for x in loop_str.split() if x.isdigit()]
total=sum_digits
print("List:", total, "=", sum(total))
Run Code Online (Sandbox Code Playgroud)

The*_*ars 5

我对你的代码进行了一些编辑,结果如下:

loop_str="a1B2c4D4e6f1g0h2I3"
sum_digits = [int(x) for x in loop_str if x.isnumeric()]
total = sum(sum_digits)
print(total)
Run Code Online (Sandbox Code Playgroud)

输出

23
Run Code Online (Sandbox Code Playgroud)

请注意,无需更改.isdigit().isnumeric()