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)
Formatting Multiple String Data Using '()' is not essential to print the formatted output of a single string variable when using the '%' symbol. But if you want to format two or more strings using '%' then use '()' to define the group of string values.
"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.
2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.
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}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With