Adding strings of numbers

4

Well, I have a string of the sort a = ("1234") and I wanted to separate those numbers so I would add them, like this: 1 + 2 + 3 + 4 How can I do this? Thanks for any help:)

    
asked by anonymous 16.03.2015 / 18:26

1 answer

6

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 characters of the string converted to number and then adds each element of 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 that sum will be 10.

EDIT

As you said you can not use list compression, another possible way is to check element by element within a for and make that 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) of list compression.

    
16.03.2015 / 18:31