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

Time:02-16

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))

CodePudding user response:

I have edited your code a little and the result is what follows:

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

Output

23

Note that there is no need to change .isdigit() to .isnumeric()

CodePudding user response:

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
  • Related