0

I have a string of numbers, for example 12458960. How can I go about adding them so that it would be 1+2+4+5+8+9+6+0 = 35

I have the numbers already recorded into a variable called ccn. I just need to get the sum now. I tried adding the string numbers using,

ccn[0]+ccn[1]+ccn[2]+ccn[3]+ccn[4]+ccn[5]+ccn[6]+ccn[7]

But that didnt work.

Any help would be much appreciated.

  • 2
    Please update your question with the code you have tried. You must have more code than: `ccn[0]+ccn[1]+ ...` – quamrana May 26 '20 at 14:05
  • Also add what is wrong or what error you are getting. I have a feeling that error could lead you to the solution... – Tomerikoo May 26 '20 at 14:06
  • If all the elements of string are numbers then try this `sum(map(int,num))` else look at @Tomerikoo 's comment. – Ch3steR May 26 '20 at 14:07
  • Hi, thanks for the help everyone, I managed to sort this one out, but will take note of your comments for future notice! – liam letts May 26 '20 at 18:33

3 Answers3

1

You can do this:-

a = '12458960'
res = sum(map(int, a))
print(res)

Output:-

35
Milan Cermak
  • 7,476
  • 3
  • 44
  • 59
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
1

Try with this one liner:

a = '12458960'
print (sum(int(i) for i in a))
Prateek Dewan
  • 1,587
  • 3
  • 16
  • 29
0

Here is a very basic way:

num = '123458960'
number = 0
for n in num:
    number += int(n)
print(number)
Red
  • 26,798
  • 7
  • 36
  • 58