Pr0cl1v1ty
Pr0cl1v1ty

Reputation: 207

How do I add a string of numbers in python

For instance if I have the string entered 345. I want them to be added 3 + 4 + 5. I've seen this here before just can't seem to find it again. Thanks!

Upvotes: 2

Views: 24302

Answers (5)

Devin Jeanpierre
Devin Jeanpierre

Reputation: 95626

Maybe it's my Scheme getting to me, but I'd use map here. map(int, s) says "take this sequence but with all its elements as integers". That is, it's the same as [int(x) for x in s], but faster to read/type.

>>> x = "345"
>>> sum(map(int, x))
12

Upvotes: 12

Ale
Ale

Reputation: 443

What unutbu said plus, if the number is an int, not a string:

num = 345    
sum([int(x) for x in str(num)])

Upvotes: -1

Achim
Achim

Reputation: 15722

data = "345"
print sum([int(x) for x in data])

Upvotes: 6

Sven Marnach
Sven Marnach

Reputation: 602775

s = raw_input()
print sum(int(c) for c in s.strip())

Upvotes: 6

unutbu
unutbu

Reputation: 881037

In [4]: text='345'

In [5]: sum(int(char) for char in text)
Out[5]: 12

or if you want the string 3+4+5:

In [8]: '+'.join(char for char in text)
Out[8]: '3+4+5'

Upvotes: 1

Related Questions