You can pad a string on the left or right with the string methods rjust and ljust.
If you want to do the formatting with a format string, and particularly if you are setting float accuracy at the same time, the format string syntax is useful.
You should have seen how to set float precision in a format string:
>>> x = 21.2468 >>> print('x = {:.2f}'.format(x)) 21.25
This is one form of formatting that comes after the : inside braces in a format string.
Even simpler is right justification:
>>> print('|{:9}|'.format(21.2468)) | 21.2468|
This can be combined with setting float precision:
>>> print('|{:9.3f}|'.format(21.2468)) | 21.247|
Note that the . character is counted in the width!
Justification with padding works with the string conversion of any data:
>>> print('|{:4}|'.format('yes')) | yes| >>> print('|{:7}|'.format('yes')) | yes| >>> print('|{:1}|'.format('yes')) |yes|
The last example illustrates that the field width is ignored if it is too small.
While right justification is the default, any of the symbols <, > and ^ can be placed right after the colon to choose left, right, or centered justification:
>>> '|{:<7.1f}|'.format(21.2468) '|21.2 |' >>> '|{:>7.1f}|'.format(21.2468) '| 21.2|' >>> '|{:^7.1f}|'.format(21.2468) '| 21.2 |'
Of course centering with an odd number of blanks cannot be perfect.
There is a whole mini-language for format strings. We have covered some of the most common parts, but far from all.
There is a new (Python 3.6+) concise formatting scheme that works only with literal (quote-delimited) strings by preceding the first quote with f. The substitutions inside are for local variables, whose names are embedded just inside the curly braces of individual substitutions:
>>> word = 'best' >>> x = 21.2468 >>> f'The {word} value is {x:.2f}!!' 'The best value is 21.25!!' >>> print(f'|{word:<6}|\n|{word:>6}|\n|{word:^6}|') |best | | best| | best |
There are more restrictions with the formatting in f-strings than with format strings used with the format method, but they work with all the basic editing modifications discussed here.