CentAu
CentAu

Reputation: 11200

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.

Upvotes: 15

Views: 13178

Answers (4)

Swati Srivastava
Swati Srivastava

Reputation: 1157

Python allows multiple format specifiers. The detailed discussion of this can be read on PEP 3101 – Advanced String Formatting.

As for your answer, the required command is

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

Upvotes: 2

PacketLoss
PacketLoss

Reputation: 5746

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.

Upvotes: 9

fractals
fractals

Reputation: 856

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

Upvotes: 16

FlorianGD
FlorianGD

Reputation: 2436

Yes, but you need first to specify the width and then the precision. The comma is used to separate thousands, so do not use it here:

>>> for v in values: print(f'{v:<10.2} value')
1.2e+01    value
1.4e+01    value

Upvotes: 4

Related Questions