Can one output something other than 'nan' for not a number values?

Cameron Simpson cs at cskk.id.au
Sat Feb 17 00:05:52 EST 2024


On 16Feb2024 22:12, Chris Green <cl at isbd.net> wrote:
>I'm looking for a simple way to make NaN values output as something
>like '-' or even just a space instead of the string 'nan'.  This would
>then make it much easier to handle outputting values from sensors when
>not all sensors are present.
>
>So, for example, my battery monitoring program outputs:-
>
>    Battery Voltages and Currents
>    Leisure Battery - 12.42 volts  -0.52 Amps
>    Starter Battery - 12.34 volts  -0.01 Amps
>
>If the starter battery sensor has failed, or is disconnected, I see:-
>
>    Battery Voltages and Currents
>    Leisure Battery - 12.42 volts  -0.52 Amps
>    Starter Battery -   nan volts    nan Amps
>
>
>What I would like is for those 'nan' strings to be just a '-' or
>something similar.
>
>Obviously I can write conditional code to check for float('nan')
>values but is there a neater way with any sort of formatting string or
>other sort of cleverness?

The simplest thing is probably just a function writing it how you want 
it:

     def float_s(f):
         if isnan(f):
             return "-"
         return str(f)

and then use eg:

     print(f'value is {float_s(value)}')

or whatever fits your code.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list