We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,478 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

adding numbers together in a string

I know python has math functions like 5+6 and 5*6 and 5/6 etc...but I have something like this:
x=575124357

and need to add them all together:
5+7+5+1+2+4+3+5+8=40

2
Contributors
3
Replies
38 Minutes
Discussion Span
4 Years Ago
Last Updated
4
Views
kiddo39
Junior Poster in Training
50 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

We help those who show a little effort at first.

Hint, convert x to a string and iterate the string summing up the int value of each character.

vegaseat
DaniWeb's Hypocrite
Moderator
6,478 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,612
Skill Endorsements: 37

Something like this will work, I just have to get it to the point that it does it without the 'raw_input'......

>>>sum([int(i) for i in raw_input("Enter integer: ")])
Enter integer:1234567
28
kiddo39
Junior Poster in Training
50 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Wait, I think I've got it:

>>>x=1234567
>>>sum(int (i) for i in str(x)])
28
kiddo39
Junior Poster in Training
50 posts since Nov 2008
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0770 seconds using 2.66MB