Sujet : Re: Can one output something other than 'nan' for not a number values?
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 17. Feb 2024, 02:13:48
Autres entêtes
Organisation : Stefan Ram
Message-ID : <formatting-20240217020913@ram.dialup.fu-berlin.de>
References : 1
Chris Green <
cl@isbd.net> writes:
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
This solution does not take the various formatting specifiers into
account correctly, but shows a broad outline of a possible approach.
main.py
import string
import math
class MyFormatter( string.Formatter ):
def format_field( self, value, format_spec ):
if isinstance( value, float )and value != value: value = '-'
return super().format_field( value, format_spec )
fmt = MyFormatter()
a = math.nan
b = 2.3
print( fmt.format( '{a}, {b}', a=a, b=b))
sys.stdout
-, 2.3