Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using string.format() to format some numbers into strings. Does format() have an option to show a specific text (e.g. 'not available') instead of nan? I couldn't find it. Or would I have to do the replacement manually?

To clarify the point raised in the comments, a question by a similar title but different context was asked here. My question is different because the author of that question wanted to get 'nan' as output, but was getting something else because of a bug that's since been fixed.

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

like image 762
Pythonista anonymous Avatar asked Jan 18 '16 10:01

Pythonista anonymous


1 Answers

I don't think you can achieve this with format, or at least, I don't know how. The only way I know it can be done is to subclass float, like this:

from math import isnan

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

Following which, you can get:

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

If you want the representation of a to show up as "Not available" on the interpreter, then you'll have to override __repr__ instead.

Alternate hack

Why not just call replace on the formatted string? (assuming there's no other string portions in there that read "nan").

>>> a = float('nan')
>>> print('This number is ' + ('%0.2f' % a).replace('nan', 'not available'))
This number is not available
like image 138
Praveen Avatar answered Sep 29 '22 18:09

Praveen