18

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

tubafranz
  • 181
  • 1
  • 1
  • 6
  • 1
    Is there a particular reason you want lowercase booleans? Is this [JSON](https://docs.python.org/2/library/json.html)-related, for example? – jonrsharpe Aug 18 '14 at 10:36
  • 3
    No, `str.format()` will not transform the case of boolean values; you'd need to do so manually. Why do you need this? – Martijn Pieters Aug 18 '14 at 10:37
  • `if mybool: str = 'true' else: str = 'false'` – Unihedron Aug 18 '14 at 10:38
  • @Unihedron: `boolval = 'true' if mybool else 'false'`. Or just `str(mybool).lower()`.. – Martijn Pieters Aug 18 '14 at 10:40
  • @MartijnPieters My comment was not intended as an actual solution, just a hint to that the straightforward approach is to conditionally assign string based on boolean. I don't believe there's a library method for this. And it's not too difficult. Also for tubafranz, please take a [tour]. – Unihedron Aug 18 '14 at 10:41
  • 2
    `"ftarlusee"[myVar::2]` for extra fun :) – John La Rooy Aug 18 '14 at 10:42
  • OK, I just wanted to make sure I have to do it manually. I thought somehow it was possible to "configure" python to have such behaviour, because I wanted to avoid the logic of needed to detect the boolean and perform the lowering of the case. I need this particular behaviour in my code. Anyway, thanks. – tubafranz Aug 18 '14 at 10:45

2 Answers2

17

You could use an expression like this

str(myVar).lower() if type(myVar) is bool else myVar
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
3

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'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 2
    As recommended in PEP8, better use `def f(x): return str(x).lower() if isinstance(x, bool) else x` instead of lambda https://www.python.org/dev/peps/pep-0008/#programming-recommendations – Touk May 02 '19 at 09:45