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.
8 Antworten
+ 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.
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.
0
Yes, I think so. But how exactly?
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 :-")))))
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():
0
Nice solution rodwynnejones
You are a great programer!
But it is a little Far away from this beginner Level, isn't it? 😉
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.
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.