How to set variable precision for new python format option

后端 未结 2 789
我在风中等你
我在风中等你 2021-01-23 13:38

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 14:38

    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 "", line 1, in 
    ValueError: Max string recursion exceeded
    

    You also can't use placeholders in the field name (so no dynamic allocation of values to slots).

提交回复
热议问题