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.

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • 1
    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). – Blckknght Sep 10 '14 at 21:24
  • @Blckknght try `print '{0} {0:g}'.format(50.0)`. They don't print the same. – Gabriel Sep 10 '14 at 21:30
  • 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. – Blckknght Sep 10 '14 at 21:30
  • @Blckknght I took the `{0:g}` format from here: http://stackoverflow.com/a/2440708/1391441 – Gabriel Sep 10 '14 at 21:31
  • 1
    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. – Blckknght Sep 10 '14 at 21:36
  • Nice tip @Blckknght, I'll keep it in mind. Thanks! – Gabriel Sep 10 '14 at 21:42

1 Answers1

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)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Great answer unubtu, minor correction, perhaps you meant: `${0}_{{t}} = {1:g} \pm {2:g}\;{3}$`? – Gabriel Sep 10 '14 at 21:24
  • 1
    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... – unutbu Sep 10 '14 at 21:27