Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.format() returns ValueError when using {0:g} to remove trailing zeros

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.

like image 882
Gabriel Avatar asked Sep 10 '14 21:09

Gabriel


1 Answers

{} 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)
like image 149
unutbu Avatar answered Sep 21 '22 23:09

unutbu