Chapter 7. Input and Output 52 Python Tutorial, Release 3.9.5 For a complete overview of string formatting with$_{str.format()}$ , see formatstrings. Here’s the same table of squares and cubes, formatted manually: 7.1.3 Manual String Formatting >>>for x in range(1,11 ): ... print(repr(x) .rjust(2),repr(x*x).rjust(3), end ='') ... # Note use of 'end' on previous line ... print(repr(x*x*x).rjust(4)) ... 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 >>> '12 '.zfill(5) '00012' >>> '-3.14 '.zfill(7) '-003.14' >>> '3.14159265359 '.zfill(5) '3.14159265359' >>>import math >>> print('The value of pi is approximately %5.3f .'%math.pi) The value of pi is approximately 3.142. The % operator (modulo) can also be used for string formatting. Given$_{'string' % values}$ , instances of$_{%}$ in$_{string}$ are replaced with zero or more elements of$_{values}$ . This operation is commonly known as string interpolation. For example: More information can be found in the old-string-formatting section. There is another method,$_{str.zfill()}$ , which pads a numeric string on the left with zeros. It understands about plus and minus signs: The$_{str.rjust()}$ method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods$_{str.ljust()}$ and$_{str.center()}$ . These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in$_{x.ljust(n)[:n]}$ .) (Note that the one space between each column was added by the way$_{print()}$ works: it always adds spaces between its arguments.) 7.1.4 Old string formatting