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!
5 Answers
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
2 Comments
ktdrv
+1.
map is more pythonic than a generator expression in this case.Pr0cl1v1ty
What is map for? and what does it do?
data = "345"
print sum([int(x) for x in data])
1 Comment
eumiro
+1, but works without square brackets as well:
sum(int(x) for x in data)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'
1 Comment
dawg
What Python shell do you use?