問題描述
我喜歡包含變量的字符串的新格式選項,但我希望有一個變量來設(shè)置整個腳本的精度,但我不知道該怎么做.舉個小例子:
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)
現(xiàn)在這就是我想用偽代碼做的事情:
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.
推薦答案
您可以嵌套占位符,其中嵌套的占位符可以在格式規(guī)范中的任何位置使用:
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 及更高版本)的自動編號;編號仍然從左到右進(jìn)行:
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)
嵌套槽先被填充;當(dāng)前的實現(xiàn)允許您最多嵌套 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
您也不能在字段名稱中使用占位符(因此不能將值動態(tài)分配給插槽).
You also can't use placeholders in the field name (so no dynamic allocation of values to slots).
這篇關(guān)于如何為新的 python 格式選項設(shè)置可變精度的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!