adding numbers together in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    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
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Following are two ways:
    Code:
    >>> x=575124357
    >>> reduce(lambda x, y: x+y, [int(s) for s in str(x)], 0)
    39
    >>> sum([int(s) for s in str(x)])
    39
    >>>

    Comment

    • Thekid
      New Member
      • Feb 2007
      • 145

      #3
      Thanks again...! I like the simpler look of the sum([int]) line so I think I'll use that.

      Comment

      Working...