我试图生成一个字符串,其中包含偶尔带有尾随零的浮点数。这是文本字符串的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
不幸的是,这会返回:
ValueError: cannot switch from automatic field numbering to manual field specification
此问题Using .format() to format a list with field width arguments报告了同一问题,但我无法弄清楚如何应用此问题的答案。
答案 0 :(得分:14)
{}
使用自动字段编号。
{0:g}
使用手动字段编号。
不要混淆两者。如果您打算使用手动字段编号,请在任何地方使用它:
text = '${0}_{{t}} = {1:g} \pm {2:g}\;{3}$'.format(xn, ccl[0], ect[0], cod)