How to add string numbers

Asked

Viewed 1,843 times

4

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

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 of string characters converted to number and then sums each element of the list.

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

EDIT

Since you said you can’t use list compression, another possible way is to check element by element within a for and make 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.

  • 1

    In this case you are using a list mechanism in comprehension?

  • 1

    can’t give me another example but without using that method? I’m sorry for the inconvenience

  • With python native libraries, I believe this is the best way... Any problem using list comprehension? .__.

  • is that in the work I need to do I can’t use list comprehension :/

  • @Crisromina, I updated with another form, I could check if it satisfies you?

  • 1

    Yes!! Thank you for helping me!:)

  • 1

    @Crisromina If the answer helped you you can accept it and vote not only on it but on anything else you find useful on the site. See the [tour].

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.