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