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

夙愿已清 提交于 2020-01-10 19:34:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!