如何为新的Python格式选项设置变量精度 [英] How to set variable precision for new python format option

查看:421
本文介绍了如何为新的Python格式选项设置变量精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢包含变量的字符串的新格式选项,但我想有一个变量,通过我的脚本设置精度,我不知道如何做到这一点。让我举个小例子:

pre $ a = 1.23456789
out_str ='a = {0:.3f}' .format(a)
print(out_str)

现在这就是我想要的在伪代码中:

  a = 1.23456789 
some_precision = 5
out_str ='a = {0 :。(some_precision)f}'。格式(a)
print(out_str)

但我不确定,如果可能的话,如果它可能是怎么样的语法。

解决方案

您可以<嵌套的占位符可以在格式规范的任何地方使用:

  out_str ='a格式(a,some_precision = some_precision)

  out_str ='a = {0:。{1}格式(a,some_precision)

Autonumbe环嵌套插槽(Python 2.7及以上)也支持;编号仍然从左到右:

  out_str ='a = {0:。{} f}'。format a,some_precision)

首先填充嵌套槽,当前的实现允许您嵌套占位符多达2个级别,所以占位符占位符中的占位符不起作用:

 > ;>> '{:。{} f}'。format(1.234,2)
'1.23'
>>>格式(1.234,2,'d')
Traceback(最近一次调用的最后一个):
文件stdin>,第1行,在< module>
ValueError:超过最大字符串递归

您也不能在字段名中使用占位符(所以没有动态分配给插槽的值)。

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)

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)

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格式选项设置变量精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆