+ 1

How do I do the sum of a the numbers entered as an string in Python ?

Like: str="012345" Now i have to find out 0+1+2+3+4+5. How do i do that? Is this related to type casting?

20th Apr 2020, 4:33 PM
Optimus Prime
Optimus Prime - avatar
5 Respuestas
+ 2
k=0 for i in str: if i in '0123456789': k += int(i)
20th Apr 2020, 4:37 PM
george
george - avatar
+ 8
Here is a solution using a comprehension: txt = "012345" print(sum([int(i) for i in txt]))
20th Apr 2020, 4:45 PM
Lothar
Lothar - avatar
+ 3
george, thank you! 👍 After posting my try here, i did some changes in code but forgot to update it here: txt = "01a2x3. 45b" print(sum([int(i) for i in txt if i.isdigit()]))
20th Apr 2020, 6:58 PM
Lothar
Lothar - avatar
+ 1
Lothar also add check in comprehension after txt if i in ‘0123456789’ and it will be just perfect)
20th Apr 2020, 5:00 PM
george
george - avatar
+ 1
Ou. perfect i am new in python but have more then 10 years c++ expirience so in c++ there are spec function, so i made such statements. In future i will be take into account that str has function isdigit
20th Apr 2020, 7:30 PM
george
george - avatar