How to set variable precision for new python format option

China☆狼群 提交于 2019-12-04 05:28:54

问题


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.


回答1:


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).




回答2:


Or you can use numbering.

a = 1.23456789
some_precision = 5
out_str = 'a = {0:.{1}f}'.format(a,some_precision)
print(out_str)

Ouptut:

a = 1.23457


来源:https://stackoverflow.com/questions/41853132/how-to-set-variable-precision-for-new-python-format-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!