Python - Using a variable as part of string formatting

Of course there is:

x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a)  # -> 1.12345

If you do not want to specify the positions (0 & 1), you just have to invert your input:

a = '{:.{}f}'.format(1.12345111, x)
#                    ^ the float that is to be formatted goes first

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

since {:1.12345111f} is invalid.


Other examples of formatting you might find interesting:

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 by @m_____z.


Assuming you're using Python 3.6, you could simply do the following:

x = 5
my_array[1, 0] = f'{a:.{x}f}'

Two ways this can be accomplished. Either by using str.format() or by using %

Where a is the number you're trying to print and x is the number of decimal places we can do:

str.format:

'{:.{dec_places}f}'.format(a, dec_places=x)

%:

'%.*f' % (x, a)