String format Signs, Alignment, and Zero-Padding
Zero-Padding
Before the width and precision numbers, we can have a "flag," which may be either zero, plus, minus, or blank.
A zero means that the number will be zero-padded:
print '%010.2f' % 3.1415926
'0000003.14'
The code above generates the following result.
The leading zero in 010 in the code above is not an octal number. 010 width specifier means that the width should be 10 and that the number should be zero-padded, not that the width should be 8.
Sign
A minus sign (-) left-aligns the value:
print '%-10.2f' % 3.1415926
The code above generates the following result.
As you can see, any extra space is put on the right-hand side of the number.
A plus (+) means that a sign (either plus or minus) should precede both positive and negative numbers (again, useful for aligning):
print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
The code above generates the following result.
Blank
A blank (" ") means that a blank should be put in front of positive numbers. This may be useful for aligning positive and negative numbers:
print ('% 5d' % 10) + '\n' + ('% 5d' % -10)
Right justify and Left justify
integerValue = 4237
print "Right justify integer (%8d)" % integerValue
print "Left justify integer (%-8d)\n" % integerValue
The code above generates the following result.