Reputation: 371
I can't figure out the correct way to make this happen.
If I have an input of float("- 4")
, I want it to return -4.0
, regardless of the blank, or whitespace. So this needs to work with other inputs like " - 4"
, as well. But I don't want this to compromise any other results of the function, so inputs like "4 -"
, or "5 5"
should not be compounded as well.
I wrote a function to try and determine if something is the correct input for my program.
def isNum(num):
try:
float(expr)
except ValueError:
return False
return True
It's just the whole input issue above that is frustrating me.
Upvotes: 1
Views: 152
Reputation: 18697
Simply strip the whitespace between -
and any digits to the right:
import re
def parse_float(inp):
return float(re.sub(r'-\s*(\d)', r'-\1', inp))
Example:
>>> parse_float(" - 4 ")
-4.0
>>> parse_float(" 5 ")
5.0
And it'll fail with ValueError
for invalid floats:
>>> parse_float(" 4 - ")
...
ValueError: invalid literal for float(): 4 -
>>> parse_float(" 5 5 ")
...
ValueError: invalid literal for float(): 5 5
Upvotes: 2