Search code examples
pythonstring-formatting

Setting precision in .format() via use of a variable


If I have the following;

dimensions={
"length" : 1.3576
}

out1 = "l = {length:.3f} mm".format(**dimensions)

However, rather than specifying .3f in the string, I would like to specify it via a variable.
The following does work:

precision=".2f"
out2 = "l = {length:"+str(precision)+"} mm"
print(out2)
out2=out2.format(**dimensions)
print(out2)

gives:

l = {length:.2f} mm
l = 1.36 mm

But this feels like a hacky job of it. Is there a better way?


Solution

  • You can nest substitutions for formatting:

    >>> precision = '.3f'
    >>> out1 = "l = {length:{precision}} mm".format(precision=precision, **dimensions)
    >>> out1
    'l = 1.358 mm'
    

    the syntax looks a little strange but totally works!