Print a float with precision right justified

Viewed 26120

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
3 Answers

Python Format Specification Mini-Language

print(f'{symbol:<5}: {name:<44} {buyprices:>10.2f}  change: {val:>5.2f}')

Output:

AXP  : American Express Company                          55.38  change: -1.15
AXR  : Amrep Corp.                                        6.54  change:  0.00

How it works:

<44 (left justified, 44 places)
>5.2f (right justified, 5 places, 2 decimal places) 
Related