Boolean to string with lowercase
28,699
Solution 1
You could use an expression like this
str(myVar).lower() if type(myVar) is bool else myVar
Solution 2
Try a lambda that you can call:
>>> f = lambda x: str(x).lower() if isinstance(x, bool) else x
>>> 'foo {} {}'.format(f(True), f('HELLO'))
'foo true HELLO'
Author by
tubafranz
Updated on July 21, 2022Comments
-
tubafranz almost 2 years
Can the
str.format()
method print boolean arguments without capitalized strings?I cannot use
str(myVar).lower()
as argument of format, because I want to preserve the case of the letters whenmyVar
is not a boolean.Please don't post solutions with conditional checks of the values of the variable.
All I am interested is in the possibility of writing the following:
"Bla bla bla {}".format(myVar)
so that the output becomes
"Bla bla bla true"
whenmyVar == True
and"Bla bla bla false"
whenmyVar == false
-
Martijn Pieters almost 10 years
isinstance(myVar, bool)
is preferred, even ifbool
cannot be subclassed further. -
Touk about 5 yearsAs recommended in PEP8, better use
def f(x): return str(x).lower() if isinstance(x, bool) else x
instead of lambda python.org/dev/peps/pep-0008/#programming-recommendations -
hitautodestruct about 2 years
str(myVar).lower() if isinstance(myVar, bool) else myVar