开发者

How do I add a string of numbers in python

For instance if I have the string enter开发者_如何学Goed 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!


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


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


data = "345"
print 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'


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜