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

I am given a string which is loop_str="a1B2c4D4e6f1g0h2I3" and have to write a code that adds up all the digits contained in 'loop_str', and then print out the sum at the end. The sum is expected to be saved under a variable named 'total'. The code I have written above although is reaching the correct answer, I am struggling on having to define total and create a for loop for this specific task.

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


Solution 1:[1]

you can extract all integers numbers like this:

import re

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

output:

364584

you should use regex to extract the integers from text like the above then sum all of them in the list.

if you want just digits you can remove + from regex like this:

import re

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

output:

48

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1