I have boolean values in my database and within a Django project I am printing them to a pdf. Its very minor but id like them to print as yes/no rather than true/false.
I know that I could use yesno if I was outputting booleans in a template:
https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#yesno
But I am outputting these within a function. I also know I could use an if/else statement, but was hoping for something a bit cleaner.
IE - Is there a short, clean way to convert boolean values to custom strings.
Thank you.
bools = ('no','yes')
value = True
print(f'The value is {bools[value]}')
This uses the fact that python booleans are actually stored as ints with False == 0 and True == 1 to index into a tuple of values. Indexing the bools tuple by the boolean that you are printing then retrieves the corresponding value from the tuple. bools[False] aka bools[0] == 'no' and bools[True] aka bools[1] == 'yes'.
>>> value = True
>>> value = 'yes' if value else 'no'
>>> print(value)
'yes'
If you have a list of values;
>>> values = [True, False, False, True]
>>> values = ['yes' if val else 'no' for val in values]
>>> print(values)
['yes', 'no', 'no', 'yes']
This is a new favorite of mine, it works because in python True == 1 and False == 0 ;
# single
value = ('no', 'yes')[value]
# multi
values = [('no', 'yes')[val] for val in values]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With