2

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 5

12

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
Sign up to request clarification or add additional context in comments.

2 Comments

+1. map is more pythonic than a generator expression in this case.
What is map for? and what does it do?
6
s = raw_input()
print sum(int(c) for c in s.strip())

Comments

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

1 Comment

+1, but works without square brackets as well: sum(int(x) for x in data)
1
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

What Python shell do you use?
-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.