python - .format() 使用 {0 :g} to remove trailing zeros 时返回 ValueError

标签 python string formatting floating-point-precision

我正在尝试生成一个字符串,其中包含一个带有尾随零的偶尔 float 。这是文本字符串的 MWE,我尝试使用 {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

不幸的是,这会返回:

ValueError: cannot switch from automatic field numbering to manual field specification

这个问题Using .format() to format a list with field width arguments报告了相同的问题,但我不知道如何将那里给出的答案应用于此问题。

最佳答案

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

不要将两者混为一谈。如果您要使用手动字段编号,请在任何地方使用它:

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

关于python - .format() 使用 {0 :g} to remove trailing zeros 时返回 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775197/

相关文章:

python - 如何在 Docker 中运行flask_migrate

逐字符异或加密的Python '\x0e'

在 c 中的 sscanf 中选择格式

Python 将变量视为文字/原始字符串

javascript - React 在渲染之前为字符串的特定部分提供样式?

C++ Stringstream 给变量赋了错误的值?

c# - 在 C# 中的字符串中找到 {0} 是什么意思?

python - 无法在虚拟主机 apache 上执行 proxy.cgi

python - 在 pandas 中随机更改行

android - 有没有办法在 Android Studio 中整齐地包装代码?