How to set variable precision for new python format option(如何为新的 python 格式选项设置可变精度)
问题描述
我喜欢包含变量的字符串的新格式选项,但我希望有一个变量来设置整个脚本的精度,但我不知道该怎么做.举个小例子:
I am loving the new format option for strings containing variables, but I would like to have a variable that sets the precision through out my script and I am not sure how to do that. Let me give a small example:
a = 1.23456789
out_str = 'a = {0:.3f}'.format(a)
print(out_str)
现在这就是我想用伪代码做的事情:
Now this is what I would want to do in pseudo code:
a = 1.23456789
some_precision = 5
out_str = 'a = {0:.(some_precision)f}'.format(a)
print(out_str)
但我不确定,是否可能以及语法是否可能.
but I am not sure, if it is possibly and if it is possibly how the syntax would look like.
推荐答案
您可以嵌套占位符,其中嵌套的占位符可以在格式规范中的任何位置使用:
You can nest placeholders, where the nested placeholders can be used anywhere in the format specification:
out_str = 'a = {0:.{some_precision}f}'.format(a, some_precision=some_precision)
我在那里使用了命名占位符,但您也可以使用编号插槽:
I used a named placeholder there, but you could use numbered slots too:
out_str = 'a = {0:.{1}f}'.format(a, some_precision)
也支持嵌套槽(Python 2.7 及更高版本)的自动编号;编号仍然从左到右进行:
Autonumbering for nested slots (Python 2.7 and up) is supported too; numbering still takes place from left to right:
out_str = 'a = {0:.{}f}'.format(a, some_precision)
嵌套槽先被填充;当前的实现允许您最多嵌套 2 层占位符,因此在占位符中使用占位符是行不通的:
Nested slots are filled first; the current implementation allows you to nest placeholders up to 2 levels, so using placeholders in placeholders in placeholders doesn't work:
>>> '{:.{}f}'.format(1.234, 2)
'1.23'
>>> '{:.{:{}}f}'.format(1.234, 2, 'd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Max string recursion exceeded
您也不能在字段名称中使用占位符(因此不能将值动态分配给插槽).
You also can't use placeholders in the field name (so no dynamic allocation of values to slots).
这篇关于如何为新的 python 格式选项设置可变精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为新的 python 格式选项设置可变精度
基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01