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'
Share:
28,699
tubafranz
Author by

tubafranz

Updated on July 21, 2022

Comments

  • tubafranz
    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 when myVar 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" when myVar == True and "Bla bla bla false" when myVar == false

  • Martijn Pieters
    Martijn Pieters almost 10 years
    isinstance(myVar, bool) is preferred, even if bool cannot be subclassed further.
  • Touk
    Touk about 5 years
    As 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
    hitautodestruct about 2 years
    str(myVar).lower() if isinstance(myVar, bool) else myVar