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 :)
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 :)
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.
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.
Browser other questions tagged python-2.7
You are not signed in. Login or sign up in order to post.
In this case you are using a list mechanism in comprehension?
– CSAnimor
can’t give me another example but without using that method? I’m sorry for the inconvenience
– CSAnimor
With python native libraries, I believe this is the best way... Any problem using list comprehension? .__.
– Felipe Avelar
is that in the work I need to do I can’t use list comprehension :/
– CSAnimor
@Crisromina, I updated with another form, I could check if it satisfies you?
– Felipe Avelar
Yes!! Thank you for helping me!:)
– CSAnimor
@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].
– Maniero