3 ms·
From reading the comments in the discussion here, I'm curious why the f-string syntax is so all-over-the-place? - f"{foo}" uses the default format - f"{foo
by CGamesPlay 6y ago
From reading the comments in the discussion here, I'm curious why the f-string syntax is so all-over-the-place?
- 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?
- pansa2 6y agoYeah, there seem to be a number of special cases. 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/msg341732 https://bugs.python.org/msg341732
- matmann2001 6y agoWhat if your format string started with "r" or "=", or was simply just one of those characters?
- dragonwriter 6y ago!r is one of a class of conversion flags, others are !a which uses ascii(), !s which uses str(). “=” in the format-spec (the thing that comes after the “:”) is the numeric padding alignment specifier (other alignment specifiers are left “<”, right “>”, and center “^”.)
- CGamesPlay 6y agoOh, neat, so I can stack them: 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}")
- hannibalhorn 6y agoYou really have to understand how it's translated into actual code, and of course it's Python, so there's some legacy syntax to take into account. A `:` just means call format(lhs, rhs), for example. You 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.