Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f-string, multiple format specifiers

Is it possible to use multiple format specifiers in a Python f-string?

For example, let's say we want to round up numbers to two decimal points and also specify a width for print.

Individually it looks like this:

In [1]: values = [12.1093, 13.95123]

In [2]: for v in values: print(f'{v:.2}')
1.2e+01
1.4e+01

In [3]: for v in values: print(f'{v:<10} value')
12.1093    value
13.95123   value

But, is it possible to combine both?

I tried:

for v in values: print(f'{v:.2,<10} value')

But I got Invalid format specifier error.

like image 770
CentAu Avatar asked Jan 24 '20 05:01

CentAu


2 Answers

You want

for v in values: print(f'{v:<10.2} value')

Detailed rules can be found in Format String Syntax:

The general form of a standard format specifier is:

format_spec ::= [[fill]align][sign][#][0][width][grouping_option][.precision][type]

For your case, you want the [align] and [.precision].

like image 73
fractals Avatar answered Oct 01 '22 13:10

fractals


Dependent on the result you want, you can combine them normally such as;

for v in values: print(f"{v:<10.2} value")

#1.2e+01    value
#1.4e+01    value

However, your result does not seem like the result you're looking for.

To force the fixed notation of the 2 you need to add f:

for v in values: print(f"{v:<10.2f} value")

#12.11      value
#13.95      value

You can read more on format specifications here.

like image 32
PacketLoss Avatar answered Oct 01 '22 11:10

PacketLoss