Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using f-strings to format a boolean

Tags:

People also ask

What is f-string formatting?

Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and curly braces containing expressions that will be replaced with their values. The expressions are evaluated at runtime and then formatted using the __format__ protocol.

How do you format a boolean in Python?

Use a formatted string literal to perform string formatting with booleans, e.g. result = f'Subscribe to newsletter: {checkbox_checked}' . Formatted string literals let us include expressions and variables inside of a string by prefixing the string with f .

What is f {} in Python?

In Python source code, an f-string is a literal string, prefixed with 'f', which contains expressions inside braces. The expressions are replaced with their values.

Is F-string faster than format?

f-strings are faster than both %-formatting and str. format() . At runtime, each expression inside the curly braces gets evaluated within its own scope, and then it's put together into the final string.


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.