tubafranz
tubafranz

Reputation: 319

Boolean to string with lowercase

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

Upvotes: 20

Views: 41783

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174692

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'

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304393

You could use an expression like this

str(myVar).lower() if type(myVar) is bool else myVar

Upvotes: 20

Related Questions