Question

Does anyone know of a python string-to-float parser that can cope with MSVC nan numbers (1.#QNAN)? Currently I'm just using float(str) which at least copes with "nan".

I'm using a python script to read the output of a C++ program (runs under linux/mac/win platforms) and the script barfs up when reading these values. (I did already find a C++ library to output the values consistently across platforms, but sometimes have to compare past results, so this still occaisionally pops up.)

Was it helpful?

Solution

Since you have to deal with legacy output files, I see no other possibility but writing a robust_float function:

def robust_float(s):
    try:
        return float(s)
    except ValueError:
        if 'nan' in s.lower():
            return float('nan')
        else:
            raise
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top