Of course have:
x = 5 a = '{1:.{0}f}'.format(x, 1.12345111) print(a)
If you do not want to specify positions ( 0 and 1 ), you just need to invert your input:
a = '{:.{}f}'.format(1.12345111, x)
This is because the first argument to format() goes to the first (outermost) bracket of the string.
As a result, the following fails :
a = '{:.{}f}'.format(x, 1.12345111)
because {:1.12345111f} not valid.
Other formatting examples that may interest you:
a = '{:.{}{}}'.format(1.12345111, x, 'f') # -> 1.12345 a = '{:.{}{}}'.format(1.12345111, x, '%') # -> 112.34511% a = '{:.{}}'.format(1.12345111, '{}{}'.format(x, 'f')) # -> 112.34511%
Finally, if you are using Python3.6, see the excellent f-strings answer @m_____z .
Ev. Kounis
source share