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?

Asked By: Basj

||

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
Answered By: sj95126

Yes, using exception handling. This handles empty string (ValueError) and when x == None (TypeError).

try:
    y = float(x)
except Exception:
    y = None
Answered By: Filip Hanes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.