Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Using a variable as part of string formatting [duplicate]

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)
like image 495
shafuq Avatar asked Dec 21 '17 16:12

shafuq


People also ask

How do I format multiple strings in Python?

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.

What does {: 3f mean in Python?

"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.

How do you use %s in Python?

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.

What is .2f in Python?

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.


2 Answers

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.

like image 147
Ma0 Avatar answered Oct 11 '22 08:10

Ma0


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

x = 5
my_array[1, 0] = f'{a:.{x}f}'
like image 21
m_____z Avatar answered Oct 11 '22 06:10

m_____z