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.
g
. Trailing zeros in a float literal don't mean anything, so546.3500
is exactly the same number as546.35
(and they'll both print out the same, whether that's the way you want or not). – Uritaprint '{0} {0:g}'.format(50.0)
. They don't print the same. – Disremember{:0g}
rather than{0:g}
? I'm not sure the former is very useful, but it is valid. – Urita{0:g}
format from here: https://mcmap.net/q/100054/-formatting-floats-without-trailing-zeros – Disremember0
is just carried over from that post (with was formatting just one value. I'd suggest using"${}_{{t}} = {:g} \pm {:g}\;{}$"
as your format string then, using automatic numbering everywhere. It's only when you mix automatic and manual numbering that you get an error. My comments were asking if the exception due to the numbering were hiding some deeper issue (where the formatting wouldn't work as you want), but it sounds like{:g}
will do exactly what you're wanting. – Urita