By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,907 Members | 1,932 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,907 IT Pros & Developers. It's quick & easy.

adding numbers together in a string

Thekid
100+
P: 145
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
Feb 5 '09 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Following are two ways:
Expand|Select|Wrap|Line Numbers
  1. >>> x=575124357
  2. >>> reduce(lambda x, y: x+y, [int(s) for s in str(x)], 0)
  3. 39
  4. >>> sum([int(s) for s in str(x)])
  5. 39
  6. >>> 
Feb 5 '09 #2

Thekid
100+
P: 145
Thanks again...! I like the simpler look of the sum([int]) line so I think I'll use that.
Feb 5 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.