python - .format() 使用 {0 :g} to remove trailing ze

我正在尝试生成一个字符串,其中包含一个带有尾随零的偶尔 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/

相关文章:

javascript - 在Javascript中使链接可点击?

Python - 为字符串格式化运算符解包列表的简短方法?

python - 使用其 API 和 Python 在 Google 表格电子表格中设置单元格格式

c# - DateTime.ToString 格式

python - python - 如何使用单行将列表/元组转换为python中的空格分隔字符串?

java - 更改 JTable 单元格颜色

python - 在python 3中将表情符号转换为Unicode,反之亦然

input - AngularJs:如何在输入中格式化数据?

C# 格式化年龄 - 关于天、周、月 - 年

c# - 格式化字母数字字符串