Issue
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
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()
Answered By - TheFaultInOurStars Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.