Replace x by float(x) if and only if it is not None
Question:
x
is either a string or None
(for example a query param from a HTTP request: request.query.get('x')
).
I’d like to transform it into a float
if not None
.
These 3 solutions work:
if x is None:
y = None
else:
y = float(x)
y = float(x) if x is not None else None # or y = float(x) if x is not None else x
y = None if x is None else float(x) # or y = x if x is None else float(x)
but probably is there a simpler way than this repetition of None
?
Answers:
You can do it this way:
>>> x = "1.23"
>>> y = x and float(x)
>>> y
1.23
>>> x = None
>>> y = x and float(x)
>>> y
Yes, using exception handling. This handles empty string (ValueError
) and when x == None
(TypeError
).
try:
y = float(x)
except Exception:
y = None
x
is either a string or None
(for example a query param from a HTTP request: request.query.get('x')
).
I’d like to transform it into a float
if not None
.
These 3 solutions work:
if x is None:
y = None
else:
y = float(x)
y = float(x) if x is not None else None # or y = float(x) if x is not None else x
y = None if x is None else float(x) # or y = x if x is None else float(x)
but probably is there a simpler way than this repetition of None
?
You can do it this way:
>>> x = "1.23"
>>> y = x and float(x)
>>> y
1.23
>>> x = None
>>> y = x and float(x)
>>> y
Yes, using exception handling. This handles empty string (ValueError
) and when x == None
(TypeError
).
try:
y = float(x)
except Exception:
y = None