I’m somewhat of a newb to programming with python so please go easy on me. I’m trying to call the string attribute rjust and also specify precision for a floating point. Here’s the code and sample output (note the 0.00 is not justified to the right):
print '%s: %s %s \tchange: %.2f' % (Instance1.symbol.ljust(5),
Instance1.name.ljust(50), Instance1.buyprices.rjust(10), Instance1.val)
OUTPUT:
AXP : American Express Company 55.38 change: -1.15
AXR : Amrep Corp. 6.540 change: 0.00
This shows an example of how to format your output with two decimal points using the older
%formatting method:the corresponding output:
Alternatively, you can use the “new and improved” .format() function which will be around for a while and is worth getting to know. The following will generate the same output as above:
Both sets of formatting directives allocate 8 spaces for your number, format it as a float with 2 digits after the decimal point. You’d have to adjust these values to fit your needs.
Using this approach to format your output will be easier I think since
.format()will give you a lot of control over the output (incl. justifying, filling, precision).