Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python bool print 'On' or 'Off' rather than 'True' or 'False'

What is the best way to make a variable that works exactly like a bool but prints On or Off rather than True or False? Currently the program is printing: Color: True, whereas Color: On would make more sense.

For the record, I initially tried to make an OnOff class that inherits from bool:

class OnOff(bool):
    def __str__(self):
        if self: return 'On'
        else: return 'Off'

From the comments, I now understand that bool is a singleton, which is why this failed miserably:

Traceback (most recent call last):
    class OnOff(bool):
TypeError: Error when calling the metaclass bases
    type 'bool' is not an acceptable base type
like image 394
Zaz Avatar asked Sep 10 '10 18:09

Zaz


People also ask

How do you change Boolean from true to False in Python?

Convert bool to string: str() You can convert True and False to strings 'True' and 'False' with str() .

How do you change a Boolean from true to False?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

Is Boolean 0 True or False Python?

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true.

How do you get Boolean output in Python?

Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.


2 Answers

print ("Off", "On")[value] works too (because (False, True) == (0,1))

like image 96
Jochen Ritzel Avatar answered Oct 21 '22 14:10

Jochen Ritzel


def Color(object):

    def __init__(self, color_value=False):
        self.color_value = color_value

    def __str__(self):
       if self.color_value:
          return 'On'
       else:
          return 'Off'

    def __cmp__(self, other):
        return self.color_value.__cmp__(other.color_value)

Although this could be overkill for you. :)

like image 39
Rahul Avatar answered Oct 21 '22 13:10

Rahul