Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Boolean To Custom String

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.

like image 685
horse Avatar asked Oct 18 '25 09:10

horse


2 Answers

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'.

like image 112
Alan Hoover Avatar answered Oct 20 '25 23:10

Alan Hoover


>>> 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]
like image 42
Sy Ker Avatar answered Oct 20 '25 22:10

Sy Ker