Reputation: 1350
I am trying to clean up some user input to a valid float type with only numbers and decimal points.
I found this approach
def to_numeric(s):
try:
s = str(s).strip()
if s is None or len(s) < 1:
return None
else:
s = ''.join(filter(lambda x: x in '.0123456789', str(s)))
if s is None or len(s) < 1:
return None
else:
s = float(s)
return s
except ValueError as detail:
return None
except Exception as detail:
return None
But the cast to float complains of
float() argument must be a string or a number, not 'filter'
How can I get the string back from the filter?
Upvotes: 2
Views: 914
Reputation: 1065
Use
s = float("".join(s))
instead of
s = float(s)
In Python 3, filter
returns an iterator and float expects str
Upvotes: 0
Reputation: 16184
filter
returns an iterable that yields single chars for that case (it iterates over the string and yields acceptable characters). Try using ''.join
to make them come back as a string:
s = ''.join(filter(lambda x: x in '.0123456789', str(s)))
s = float(s)
Upvotes: 3