convert string to float without silent NaN/Inf conversion

Posted by Peter Hansen on Stack Overflow See other posts from Stack Overflow or by Peter Hansen
Published on 2010-06-05T15:12:33Z Indexed on 2010/06/05 15:22 UTC
Read the original article Hit count: 415

Filed under:
|
|
|

I'd like convert strings to floats using Python 2.6 and later, but without silently converting things like 'NaN' and 'Inf'.

Before 2.6, float("NaN") would raise a ValueError. Now it returns a float for which math.isnan() returns True, which is not useful behaviour for my application.

Here's what I've got at the moment:

import math
def get_floats(source):
    for text in source.split():
        try:
            val = float(text)
            if math.isnan(val) or math.isinf(val):
                raise ValueError
            yield val
        except ValueError:
            pass

This is a generator, which I can supply with strings containing whitespace-separated sequences representing real numbers. I'd like it to yield only those fields which are purely numeric representations of floats, as in "1.23" or "-34e6", but not for example "NaN" or "-Inf".

Test case:

assert list(get_floats('1.23 -34e6 NaN -Inf')) == [1.23, -34000000.0]

Please suggest alternatives you consider more elegant, even if they involve "look before you leap" (which is normally considered a lesser approach in Python).

© Stack Overflow or respective owner

Related posts about python

Related posts about subjective