使用{0:g}删除尾随零时,.format()返回ValueError

Gab*_*iel 7 python string formatting floating-point-precision

我正在尝试生成一个字符串,其中包含偶尔带有尾随零的浮点数.这是文本字符串的MWE,我试图用以下方法删除它们{0:g}:

xn, cod = 'r', 'abc'
ccl = [546.3500, 6785.35416]
ect = [12.350, 13.643241]

text = '${}_{{t}} = {0:g} \pm {0:g}\;{}$'.format(xn, ccl[0], ect[0], cod)
print text
Run Code Online (Sandbox Code Playgroud)

不幸的是,这回归

ValueError: cannot switch from automatic field numbering to manual field specification
Run Code Online (Sandbox Code Playgroud)

这个问题使用.format()来格式化具有相同问题报告的字段宽度参数的列表,但我无法弄清楚如何将答案应用于此问题.

unu*_*tbu 14

{}使用自动字段编号. {0:g}使用手动字段编号.

不要混淆两者.如果您打算使用手动字段编号,请在任何地方使用它:

text = '${0}_{{t}} = {1:g} \pm {2:g}\;{3}$'.format(xn, ccl[0], ect[0], cod)
Run Code Online (Sandbox Code Playgroud)