python-2.7 – How to add strings of numbers

Question:

Well I have a string like a=("1234") and I wanted to separate these numbers in order to add them up, like this: 1+2+3+4 How can I do this? I appreciate any help 🙂

Answer:

You can do the following if the string contains only numbers:

sum([int(x) for x in a])

This line creates a list with the string characters converted to number and then adds each element in the list.

Remembering that this does not check if the string only contains numbers and adds each position of the string, for example, if I have "1234" the result of this sum will be 10.

EDIT

As you said that you cannot use list compression, another possible way is to check element by element inside a for and do this sum, as in the following example:

soma = 0
minha_string = "123456"
for numero in minha_string:
    soma += int(numero)

This will have the same effect (and same restrictions) as list compression.

Scroll to Top