我如何将数字和字符串与 return 相加?

How would I separate numbers and from a string and return the summation of them?

我得到一个 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))

我稍微修改了你的代码,结果如下:

loop_str="a1B2c4D4e6f1g0h2I3"
sum_digits = [int(x) for x in loop_str if x.isnumeric()]
total = sum(sum_digits)
print(total)

输出

23

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

您可以像这样提取所有整数:

import re

total = sum([ int(i) for i in re.findall('(\d+)', 'a1B2c4D4e6f1g0h2I364564')])
print(a)

输出:

364584

您应该像上面那样使用正则表达式从文本中提取整数,然后在列表中对所有整数求和。

如果你只想要数字,你可以像这样从正则表达式中删除 +

import re

total = sum([ int(i) for i in re.findall('(\d)', 'a1B2c4D4e6f1g0h2I364564')])
print(a)

输出:

48