+ 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?
5 Respuestas
+ 2
k=0
for i in str:
if i in '0123456789':
k += int(i)
+ 8
Here is a solution using a comprehension:
txt = "012345"
print(sum([int(i) for i in txt]))
+ 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()]))
+ 1
Lothar also add check in comprehension after txt if i in ‘0123456789’ and it will be just perfect)
+ 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