Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
–
–
–
print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);
These are the results
True False
True False
1.000000 0.000000
1.000000e+00 0.000000e+00
Some of the %
-format type specifiers (%r
, %i
) are not available. For details see the Format Specification Mini-Language
–
–
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
To expand on the answer by phd, you can do all that without str()
-ing your booleans in the format()
call. There are some weird tricks you can exploit to do formatting for booleans with the new style of string interpolation. It also works for f-strings.
The bland, trivial case
'{},{}'.format(True, False) # 'True,False'
f'{True},{False}' # 'True,False'
Adding some formatting converts booleans to integers
Any padding length will do this. I am not sure why someone would want it to work this way.
'{:0},{:0}'.format(True, False) # '1,0'
f'{True:0},{False:0}' # '1,0'
'{:>5},{:>5}'.format(True, False) # ' 1, 0'
f'{True:>5},{False:>5}' # ' 1, 0'
String coercion can bring back the normal text
Note the !s
in there. This is the most direct equivalent to %s
. There's also !r
for __repr__()
and !a
for ASCII, but they're not particularly interesting for booleans.
'{!s:>5},{!s:>5}'.format(True, False) # ' True,False'
f'{True!s:>5},{False!s:>5}' # ' True,False'
Referring to Python string interpolation
In Python 3.6, string interpolation has been added with a new string literal f prefix
shouldBeTrue = True
print(f"shouldBeTrue={shouldBeTrue}")
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.