PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

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

 July 20, 2022     for-loop, integer, python     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing