python .format包括浮点格式

时间:2018-05-21 10:13:54

标签: python string.format

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

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

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

返回以下错误ValueError: cannot switch from automatic field numbering to manual field specification

经过一番搜索,这个问题似乎确实存在解决方案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选项的自动字段规范转换为手动字段规范,只格式化我提供的浮点变量,并保留所有其他string1-5变量未格式化。虽然我可以使用类似round()或类似numpy的东西,但这可能会导致问题,我觉得我会用.format示例更好地学习。

1 个答案:

答案 0 :(得分:3)

在您的代码中

删除舍入数字之前的零

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

注意:为什么它不起作用,你可以在{}中将索引提到{0},{1}或保留所有索引,但是你不能保留少数{}的索引和少数没有任何索引。< / p>