why does this erroneous python format produce this result and not an exception?

狂风中的少年 提交于 2019-12-11 10:48:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!