Formatted Printing in Python
Archive - Originally posted on "The Horse's Mouth" - 2010-05-25 18:19:49 - Graham EllisPython has no "printf" or "sprintf" - use the % operator on a string object which is the format string instead. Let me show you that ...
Firstly, what do we get if we do NOT format?
>>> val = 1. / 17.
>>> print val
0.0588235294118
Here it is, formatted to 4 figures after the decimal place:
>>> val24dp = "%.4f" % val
>>> print val24dp
0.0588
And with a total field width of 8 characters, of which 4 are after the decimal place (the 8 is a total width and NOT the number of places before!)
>>> f2 = "A seventeenth is %8.4f to 4 places" % val
>>> print f2
A seventeenth is 0.0588 to 4 places
Whole numbers are formatted with a "d" - that stands for "decimal" as opposed to "x" for hexadecimal, or the letter "o" for Octal.
>>> n = 5
>>> vv = "There are %3d in stock" % n
>>> print vv
There are 5 in stock
And if I want to format several values at the same time, I can do so by using multiple % based place holders, and then specifying a tuple for formatting.
>>> vx = "There are %d in stock at %.4fp each" % (n,val)
>>> print vx
There are 5 in stock at 0.0588p each