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

Grant Edwards grante at panix.com
Sat Feb 17 18:39:33 EST 2024


[Posts via slrn and my GMail account aren't showing up, so I guess I'll 
try
subscribing from a different e-mail address.]

On 2024-02-17, Cameron Simpson via Python-list <python-list at python.org> 
wrote:
> 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'.  [...]
>> 
>>    Battery Voltages and Currents
>>    Leisure Battery - 12.42 volts  -0.52 Amps
>>    Starter Battery - 12.34 volts  -0.01 Amps

> 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)

Since he's obviously using one of the float formatting mechanisms to
control the number of columsn and decimal places, I doubt str(f) will
meet the need.

I tried monkey-patching the float type's __format__ method, but it's
immutable.

Is float.__format__() what's used by f-strings, the '%' operator, etc.?


-- 
Grant


More information about the Python-list mailing list