Search code examples
python-3.xf-string

Using f-strings to format a boolean


I expect that someone has answered this, but I've searched on this topic and I can't find an answer.
Using Python3.6+, I want to format a boolean variable to a fixed width using an f-string. I have tables of results and want a fixed width across both True and False values, so I want a formatted string width five characters wide. The following would make sense:

print(f"X = {True:5s}")

But get:

ValueError: Unknown format code 's' for object of type 'bool'

I understand that I can force a string conversion with:

print(f"X = {str(True):5}")

But it seems odd that one can't use a format specifier code. Is there some variant of the syntax that I am missing? I've read PEP498 but it never even mentions booleans.


Solution

  • Using conversion flags:

    print(f"X = {True!s:^5}")

    or

    print(f"X = {True!r:^5}")

    or

    print(f"X = {True!a:^5}")

    where !s calls str(), !r calls repr() and !a calls ascii() on the value.