Python - using a variable as part of string formatting

I was looking for an answer, but since it is a little specific, it cannot find the answer. A simple question for experts (hopefully).

I want to be able to use the int variable instead of the number (5) used in the code below. I hope there is a way, otherwise I will have to put my code in blocks , if which I try to avoid, if possible (I do not want it to pass the condition every time in my loop).

my_array[1, 0] = '{0:.5f}'.format(a) 

Is there a way to write the code below using a type variable:

 x = 5 my_array[1, 0] = '{0:.xf}'.format(a) 

Any help would be appreciated!

+8
python string-formatting
source share
4 answers

Of course have:

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

If you do not want to specify positions ( 0 and 1 ), you just need to invert your input:

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

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 .

+16
source share

Assuming you are using Python 3.6, you can simply do the following:

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

There are two ways to do this. Either using str.format (), or using%

Where a is the number you are 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) 
+3
source share
 x=5 f='{0:.'+str(x)+'f}' my_array[1, 0] = f.format(a) 
0
source share

All Articles