placing f-strings inside of f-strings

70 Views Asked by At

I have a number 1234567.12. I'm trying to center it in a field of 20, with 3 decimal places, commas as separators and pad the left and right sides with *. Here's what I did: (Python3.11)

value = 1234567.12
y = f'{value:,.3f}'
x = f'{y:*^20}'

which is also equivalent to:

x = f'{f"{value:,.3f}":*^20}'

is there a cleaner syntax?

1

There are 1 best solutions below

2
blhsing On BEST ANSWER

According to the specifications of the format mini-language:

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

you can just put fill (*), align (^) and width (20) before grouping_option (,):

x = f'{value:*^20,.3f}'