我正在尝试生成一个字符串,其中包含一个带有尾随零的偶尔 float 。这是文本字符串的 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:g}
使用手动字段编号。
不要将两者混为一谈。如果您要使用手动字段编号,请在任何地方使用它:
text = '${0}_{{t}} = {1:g} \pm {2:g}\;{3}$'.format(xn, ccl[0], ect[0], cod)
关于python - .format() 使用 {0 :g} to remove trailing zeros 时返回 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775197/