Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading