.format() returns ValueError when using {0:g} to r

2019-02-09 14:36发布

I'm trying to generate a string that involves an occasional float with trailing zeros. This is a MWE of the text string and my attempt at removing them with {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

Unfortunately this returns:

ValueError: cannot switch from automatic field numbering to manual field specification

This question Using .format() to format a list with field width arguments reported on the same issue but I can't figure out how to apply the answer given there to this problem.

1条回答
在下西门庆
2楼-- · 2019-02-09 15:06

{} uses automatic field numbering. {0:g} uses manual field numbering.

Don't mix the two. If you are going to use manual field numbering, use it everywhere:

text = '${0}_{{t}} = {1:g} \pm {2:g}\;{3}$'.format(xn, ccl[0], ect[0], cod)
查看更多
登录 后发表回答