I searched for an answer but since it is a bit specific couldnt find an answer. A simple question for the experts (I hope).
I want to be able to use a int variable instead of the number (5) used in the code below. I hope there is a way or else I will have to put my code within if blocks which i am trying to avoid if possible (i don’t want it to go through a condition everytime in my loop).
my_array[1, 0] = '{0:.5f}'.format(a)
Is there a way for me to write the code below using a variable like:
x = 5
my_array[1, 0] = '{0:.xf}'.format(a)
Any help will be appreciated!
Solution:
Of course there is:
x = 5
a = '{1:.{0}f}'.format(x, 1.12345111)
print(a) # -> 1.12345
Note that the following fails:
a = '{:.{}f}'.format(x, 1.12345111)That is because the first argument to
format()goes to the
first (outermost) bracket of the string and since{:1.12345111f}is invalid, an Error is raised.
If you do not want to specify the positions (0 & 1), you have to invert your input:
a = '{:.{}f}'.format(1.12345111, x)
# ^ now the number goes first.
