Comment by cloudbonsai
3 days ago
You haven't seen the full depth yet. Suppose that you encountered with this line:
print(f"{n:.2g}")
What will it print? Here is the official explanation from https://docs.python.org/3.12/library/string.html#formatspec:
g - General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude. A precision of 0 is treated as equivalent to a precision of 1.
The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then, if m <= exp < p, where m is -4 for floats and -6 for Decimals, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it, unless the '#' option is used.
With no precision given, uses a precision of 6 significant digits for float. For Decimal, the coefficient of the result is formed from the coefficient digits of the value; scientific notation is used for values smaller than 1e-6 in absolute value and values where the place value of the least significant digit is larger than 1, and fixed-point notation is used otherwise.
Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.
Make sense? You now should be able to see why it's called f-string.
Yes, it's a generalisation of `%g` in f-string's ancestor printf(3). This is what people expect to find in formatting templates.
I don't know why people look at paragraphs of documentation that explain the exact results in strange edge cases (which have to exist because of the underlying complexity; in this example, Python can't change how IEEE-754 works, nor the original C printf specifier they're emulating) and conclude that this proves some strange and unexpected complexity was introduced.
When documentation isn't this thorough, people complain about that, too.
Maybe should be called “iq-string” for Interview Question string.