Search code examples
pythonstring-formatting

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.


Solution

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