.format()在使用{0:g}删除尾随零时返回ValueError [英] .format() returns ValueError when using {0:g} to remove trailing zeros

查看:554
本文介绍了.format()在使用{0:g}删除尾随零时返回ValueError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图产生一个字符串,涉及到偶尔浮动与尾随零。这是文本字符串的MWE,我试图用 {0:g} 删除它们:



<$ p $













$ ='$ {} _ {{t}} = {0:g} \ pm {0:g} \; {} $'。 b $ b打印文本

不幸的是,这返回:

  ValueError:无法从自动字段编号切换到手动字段说明

这个问题使用.format()来格式化一个带有字段宽度参数的列表在同一个问题上报告,但我无法弄清楚如何应用这个问题给出的答案。

解决方案

{} 使用自动字段编号。
{0:g} 使用手动字段编号。

不要混合两者。如果您打算使用手动字段编号,请在任何地方使用:

  text ='$ {0} _ {{t}格式(xn,ccl [0],ect [0],cod)
} {1:g} \ pm {2:g} \; {3} >


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.

解决方案

{} 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)

这篇关于.format()在使用{0:g}删除尾随零时返回ValueError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆