Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format float with padding and justification

I know I can do

> print '|{:16.3f}|\n|{:16.3f}|'.format(1, 10)
|           1.000|
|          10.000|

to pad a number so that the output is a certain number of columns, and I can do

> print '|{:<16.3f}|\n|{:<16.3f}|'.format(1, 10)
|1.000           |
|10.000          |

to left justify the formatted field. Is there a way to do both at the same time? I'd like left justification on a padded number, so my output would look like

> print '|{:<format>}|\n|{:<format>}|'.format(1, 10)
| 1.000          |
|10.000          |

where <format> is what I'm trying to solve for. Specifically, I want a 6 character formatted floating point number with 3 decimal places left justified to 16 columns. I know I could solve this with multiple string formats, but I'd like to do it all at the same time.

like image 206
bheklilr Avatar asked Sep 18 '25 02:09

bheklilr


1 Answers

You have to embed the formatted number into a wider column:

>>> print '|{:16s}|\n|{:16s}|'.format(format(1, '6.3f'), format(10, '6.3f'))
| 1.000          |
|10.000          |

I used format() function calls to format just the numbers.

Although the str.format() parser can handle filling in parameters from formatting slots, you cannot format the formatting output.

Of course, you could just add spaces to your formatting string, since you already control the width of the formatting you know there will be 10 spaces after the numbers:

>>> print '|{:6.3f}          |\n|{:6.3f}          |'.format(1, 10)
| 1.000          |
|10.000          |
like image 64
Martijn Pieters Avatar answered Sep 20 '25 17:09

Martijn Pieters