by CGamesPlay · 5y ago · 0 comments
- f"{foo}" uses the default format
- f"{foo!r}" uses repr to format
- f"{foo=}" uses a special-cased debugging introspection
- f"{foo:formatstr}" uses the default format with a custom format string
- f"{foo:{bar}}" uses a dynamic format string
It seems like `!r` and `=` should have been implemented with `:r` and `:=` instead?“=” in the format-spec (the thing that comes after the “:”) is the numeric padding alignment specifier (other alignment specifiers are left “<”, right “>”, and center “^”.)
foo = 'foo'
print(f"{foo=!r:>20}")
print(f"{foo.upper()=!r:>20}")
The `=` you pointed out is a special case, however, and not part of the alignment specification. Sadly, this means that the above snippet is not as nicely formatted as I'd like. Still, it does seem useful for these cases: print(f"{x=:.2f} {dx=:.2f} {dot_product=:.4f}")The rules for the trailing `=` case are particularly complicated:
{x=} -> "x="+repr(x)
{x=:.2f} -> "x="+format(x, ".2f")
{x=:} -> "x="+format(x, "")
{x=:!s:20} -> "x="+format(str(x), "20")
{x=:!r:20} -> "x="+format(repr(x), "20")
https://bugs.python.org/msg341732You can also actually combine those syntaxes - I often use f"{foo:%Y-%m-%d!r}" to get a quoted, properly escaped date in a specific format, for example.