Python string.format (): formatting nans as "some text"?

I use string.format()to format some numbers into strings. Is it format()possible to display specific text (for example, "unavailable") instead of nan? I could not find it. Or will I have to do a manual replacement?

To clarify the issue raised in the comments, the question was by a similar name, but a different context was requested here . I have a different question, because the author of this question wanted to get 'nan' as the output, but was getting something else due to an error that has since been fixed.

Instead, I want to understand if format () has a built-in option to replace 'nan' with another text. Of course, I fully understand that I can make the replacement myself, but I was just wondering if this was a built-in option format().

+4
source share
1 answer

I do not think that you can achieve this with help format, or at least I do not know how to do it. The only way I know to do this is to subclass float, for example:

from math import isnan

class myfloat(float):
    def __str__(self):
        if isnan(self):
            return 'Not available'
        else:
            return super(myfloat, self).__str__()

After that you can get:

>>> a = myfloat('nan')
>>> a
nan
>>> print(a)
Not available

If you want the view to aappear as "Inaccessible" in the interpreter, you need to override it instead __repr__.

replace ? (, , "nan" ).

>>> a = float('nan')
>>> print('This number is ' + ('%0.2f' % a).replace('nan', 'not available'))
This number is not available
+4

Source: https://habr.com/ru/post/1624764/


All Articles