Reputation: 207
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
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
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
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