I have a text with numbers and the problem asks to sum the numbers which appear in the string. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I have a text with numbers and the problem asks to sum the numbers which appear in the string.

It worked with natural number but not with float numbers.

28th Dec 2019, 7:58 AM
Frontend Dev Junior
Frontend Dev Junior - avatar
8 Answers
+ 2
This could be a workaround for your case: if c.isdecimal() or '.' in c: But this is not very "clean". I'm not sure, but I think you normaly have to implement your own IsNumeric() function.
28th Dec 2019, 10:55 AM
Coding Cat
Coding Cat - avatar
0
Ex: text=input ("text=") l=text. split() for c in l : if c. isdecimal() : s+=c print (s) If I have text: I have 10 years and 65 kg. - - - - - >s=75 But if I have text: I have 10 years and 65.4 kg - - - >s=10. It doesn't add 65.4 to 10.
28th Dec 2019, 8:04 AM
Frontend Dev Junior
Frontend Dev Junior - avatar
0
Yes, I think so. But how exactly?
28th Dec 2019, 1:16 PM
Frontend Dev Junior
Frontend Dev Junior - avatar
0
amended to use float too:- import re print(sum(map(lambda x: float(x), re.findall(r"\d+\.?\d+", input("Type in a string :-")))))
28th Dec 2019, 1:53 PM
rodwynnejones
rodwynnejones - avatar
0
Make a function that test every char in a loop, if accepted as numeric char or Symbol as + - and '.' And if so, return True. Make your own try. I have one ready just now. In your program you call then: if IsNumeric(c): instead off: if c.isdecimal():
28th Dec 2019, 1:54 PM
Coding Cat
Coding Cat - avatar
0
Nice solution rodwynnejones You are a great programer! But it is a little Far away from this beginner Level, isn't it? 😉
28th Dec 2019, 1:57 PM
Coding Cat
Coding Cat - avatar
0
@Thomas Granted i'm not a raw beginner...but I still class myself as a beginner. @Learning Python If you input 65 kg and not 65kg (notice the space between the number and "Kg"..then how about this:- mysum = 0 for x in input("Type in a string").split(): try: mysum += float(x) except: continue print(mysum) It will still add the int's too.
28th Dec 2019, 2:32 PM
rodwynnejones
rodwynnejones - avatar
0
rodwynnejones Readable code 👍 that's much better. And no question, that's a good solution. It's another way as the TO ask for. But he can use this, if it's ok for him to use try/except. Thanks.
28th Dec 2019, 2:50 PM
Coding Cat
Coding Cat - avatar