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

1

7

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.

Disremember answered 10/9, 2014 at 21:13 Comment(6)
I'm not sure I understand what you're trying to achieve with g. Trailing zeros in a float literal don't mean anything, so 546.3500 is exactly the same number as 546.35 (and they'll both print out the same, whether that's the way you want or not).Urita
@Urita try print '{0} {0:g}'.format(50.0). They don't print the same.Disremember
As I read the question again, did you perhaps want {:0g} rather than {0:g}? I'm not sure the former is very useful, but it is valid.Urita
@Urita I took the {0:g} format from here: https://mcmap.net/q/100054/-formatting-floats-without-trailing-zerosDisremember
Ah, so the 0 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
Nice tip @Blckknght, I'll keep it in mind. Thanks!Disremember
E
14

{} 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)
Eupepsia answered 10/9, 2014 at 21:18 Comment(2)
Great answer unubtu, minor correction, perhaps you meant: ${0}_{{t}} = {1:g} \pm {2:g}\;{3}$?Disremember
Thanks Gabriel. I wasn't sure what field numbers to use, since the original code used {0:g} twice and yet there were four arguments...Eupepsia

© 2022 - 2024 — McMap. All rights reserved.