【问题标题】:why does this erroneous python format produce this result and not an exception?为什么这种错误的 python 格式会产生这个结果而不是异常?
【发布时间】:2018-07-31 16:03:10
【问题描述】:

我发现了一个错误,导致 : 在格式中的位置不正确。

但我还不明白这种行为。为什么第二行生成两个 pi(错误的第二个值)但格式正确,而不是抛出异常?

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!

给予

pi=3.14, e=2.7183
pi=3.14, e=3.1416 wrong!

【问题讨论】:

    标签: python-2.7 format


    【解决方案1】:

    冒号前的数字是参数的索引,因此在您的第二个print 中,{0:.2f}{0:.4f} 都打印索引为 0 的相同参数,即 math.pi

    摘自Format String Syntax

    replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
    field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
    

    注意:之前的field_name,它可以是元素索引。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 2013-02-19
    • 2018-08-18
    相关资源
    最近更新 更多