Home > Back-end >  Python string formatting and padding
Python string formatting and padding

Time:06-29

I was wondering if there is a way in Python > 3.6, using f-strings, to achieve the following: I have a number 2451545.00000 which I would like to print as %.5f but at the same time I'd like to have it centre justified e.g. using f-string {' '}^{20}. Is there a way to achieve that in a single command e.g., {2451545.00000:.5{' '}^{20}} or something like that?

Thank you in advance!

CodePudding user response:

You can use ^ in the f-string:

num = 2451545.00000
print(repr(f"{num:^20.5f}")) # '   2451545.00000    '

You can read the doc for relevant information. The ^ is listed as an "align" option.

CodePudding user response:

I think what you're going for can be written as follows:

my_string = "{0:^20.5f}".format(2451545.00000000)
print(my_string)

Hope it helps.

  • Related