python .format 包括浮点格式

标签 python string.format

我已经知道 .format 很长一段时间了,但是当我尝试在如下字符串中包含浮点格式时:

"ab_{}_cd{}_e_{}_{}_{}_val={0:.5f}_{}".format(string1,str(2),string2,string3,string4, str(0.12345678),string5)

在上面的例子中,string1-5 表示这个例子中包含的随机字符串。

返回了以下错误ValueError:无法从自动字段编号切换到手动字段规范

经过一番搜索,这个问题似乎确实包含解决方案 Using .format() to format a list with field width arguments

上面的链接显示我需要格式化字符串中的所有 {} 以获得我想要的格式。我浏览了官方文档 https://docs.python.org/2/library/string.htmlhttps://docs.python.org/2/library/stdtypes.html#str.format,并没有太多解释我在寻找什么的方式。

期望的输出:

关于如何将 .format 选项的自动字段规范转换为手动字段规范的解释,仅格式化我提供的 float 变量并保留所有其他 string1-5 变量未格式化。虽然我可以只使用 round() 之类的东西或 numpy 等价物,但这可能会导致问题,我觉得我会通过 .format 示例学得更好。

最佳答案

在您的代码中删除四舍五入数字前的零

"ab_{}_cd{}_e_{}_{}_{}_val={:.5f}_{}".format(string1,str(2),string2,string3,string4,str(0.12345678),string5)

注意:它不起作用的原因是,您可以将 {} 中的索引作为 {0}、{1} 提及或保留所有索引,但您不能只保留少量带索引的 {} 和不带任何索引的少数 {}。

关于python .format 包括浮点格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50446589/

相关文章:

python - 自动维恩图文本渲染

python - 用python、库制作一个wordcloud网络(链接)?

asp.net-mvc-3 - 货币格式MVC

c# - 可以将参数的格式说明符作为另一个参数传递给 String.Format 吗?

python - 将 (X, Y) 组合列表相乘

python - TypeError : 'int' object is not subscriptable in list in python

python - 如何知道特征影响模型预测的因素

java - 如何使用 String.format() 打印两个对象

c# - 绑定(bind)到 Entry.Text 的属性 setter 无限循环

Python string.format() 百分比不四舍五入