问题
I've tracked down a bug to incorrect placement of : in a format.
But I don't yet understand the behavior. Why does the 2nd line generate two pi's (wrong 2nd value) but proper formatting, rather than throw an exception?
import math
data = math.pi, math.e
print 'pi={:0.2f}, e={:0.4f}'.format(*data)
print 'pi={0:.2f}, e={0:.4f} wrong!'.format(*data) # wrong!
gives
pi=3.14, e=2.7183
pi=3.14, e=3.1416 wrong!
回答1:
The number before the colon is the index of the arguments, so in your second print both {0:.2f} and {0:.4f} are printing the same argument of index 0, which is math.pi.
Excerpt from Format String Syntax:
replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}" field_name ::= arg_name ("." attribute_name | "[" element_index "]")*
Note the field_name before :, which can be an element index.
来源:https://stackoverflow.com/questions/51608190/why-does-this-erroneous-python-format-produce-this-result-and-not-an-exception