问题
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:
{}
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)
来源:https://stackoverflow.com/questions/25775197/format-returns-valueerror-when-using-0g-to-remove-trailing-zeros