-2

Hey guys so I have an assignment due in my intro to Python class and my teacher noted (He hasn't explained it yet) that a certain part of the output has to be right-justified via the format() function.

So far I've learned a few things regarding format, such as these:

print(format(12345.6789,'.2f'))
print(format(12345.6789,',.2f'))
print('The number is ',format(12345.6789,'10,.3f'))
print(format(123456,'10,d'))

I understand these just fine, but here's what my professor wants in my program.

This is what needs right justification:

    Amount paid for the stock:      $ 350,000
    Commission paid on the purchase:$  27,000
    Amount the stock sold for:      $ 350,000 
    Commission paid on the sale:    $   30,00
    Profit (or loss if negative):   $ -57,000

These numbers are incorrect^ I forget the actual values, but you get the point.

Here's the code for those I already have.

#Output
print("\n\n")
print("Amount paid for the stock:      $",format(stockPaid,',.2f'),sep='')
print("Commission paid on the purchase:$",format(commissionBuy,',.2f'),sep='')
print("Amount the stock sold for:      $",format(stockSold,',.2f'),sep='')
print("Commission paid on the sale:    $",format(commissionSell,',.2f'),sep='')
print("Profit (or loss if negative):   $",format(profit,',.2f'),sep='')

So how do I get those values to print right justified while the rest of the string before each is left justified?

Thank you for your help you guys are awesome as always!

  • 4
    This is the first thing in the documentation for [str.format()](http://docs.python.org/3.3/library/string.html#format-specification-mini-language). Whenever you don't know something about Python (or any language) the documentation should be your first port of call. It's extensive and accurate. Plus reading documentation is a hugely important skill to any programmer. – Gareth Latty Feb 01 '13 at 01:56
  • 1
    Also, please remove all irrelevant parts of the code. Your code snippet could be cut to about 3 lines and still convey exactly what you need to do. :) – Lenna Feb 01 '13 at 02:02
  • +1 Lattyware. But one minor quibble: He's not calling `str.format()`, so you probably should have labeled that link `format()`. (Since the docs you linked to are for `format`, `str.format`, and `Formatter`, nothing else needs to change, just the label.) – abarnert Feb 01 '13 at 02:08
  • Thank you for your help. I will check it out. I did look at many docs before coming here but did not find and exact explanation. – Vladislav Reshetnyak Feb 01 '13 at 02:20
  • I've looked at those docs, and they did not specifically show (actually there is no code examples at all) what I have to use to right justify. Please, instead of simply shunning me away could you please explain what I should do. What's the purpose of coming here if you simply make me leave and try on my own. I've done that already, I've looked at tons of questions here on formatting, and I still don't get it. – Vladislav Reshetnyak Feb 01 '13 at 02:27

2 Answers2

0

Try using this - it is in the documentation though. You will need to apply any other formatting applicable that you've already got though.

>>> format('123', '>30')
'                           123'
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

This question is a near duplicate of Align Left / Right in Python there is a modification to get it to work for you (following code is Python 3.X compatable):

# generic list name with generic values
apples = ['a', 'ab', 'abc', 'abcd']

def align_text(le, ri):
    max_left_size = len(max(le, key=len))
    max_right_size = len(max(ri, key=len))
    padding = max_left_size + max_right_size + 1

    return ['{}{}{}'.format(x[0], ' '*(padding-(len(x[0])+len(x[1]))), x[1]) for x in zip(le, ri)]

for x in align_text(apples, apples):
    print (x)

The "".format() syntax is used to replace placeholders in a string with the arguments you provide, the documentation for it is Python Docs String Formatter. I can't stress enough how amazing this is when you are creating strings with variables mixed in.

This will require you to put your left and right values in separate lists however, from your example it would be:

left_stuff = [
        "Amount paid for the stock:      $",
        "Commission paid on the purchase:$",
        "Amount the stock sold for:      $",
        "Commission paid on the sale:    $",
        "Profit (or loss if negative):   $"]

right_stuff = [
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f'),
        format(1,',.2f')]

The output is:

Amount paid for the stock:      $ 1.00
Commission paid on the purchase:$ 1.00
Amount the stock sold for:      $ 1.00
Commission paid on the sale:    $ 1.00
Profit (or loss if negative):   $ 1.00

You can get rid of the space between the $ by either removing the +1 in the function or putting the $ on the right.

Community
  • 1
  • 1
Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • That's some really advanced stuff. I've pasted it in and get a syntax error on the print x line. If I were to submit this assignment with all that fancy stuff I'm sure o be questioned. Are you sure there isn't a modifier for the format(float) part? LIke the format(1,',.2f') part? – Vladislav Reshetnyak Feb 01 '13 at 04:04
  • You are probably using python 3.X then, change the print to `print (x)` and it'll be good. That `format` part is a pretty basic string formatter, i'll link you to the documentation, but basically it replaces the placeholders `{}` with the arguments, in order, a really good way to concatenate / add to strings, I can't recommend it enough over the `+` or `,` method, except for really basic concatenations. – Serdalis Feb 01 '13 at 05:42
  • Got this: Traceback (most recent call last): File "I:\School\Python\Projects\Program 2.py", line 36, in from itertools import izip ImportError: cannot import name izip – Vladislav Reshetnyak Feb 01 '13 at 06:26
  • @litebread sorry, in python 3.X `izip` was renamed `zip` and delete the `import izip from itertools`. – Serdalis Feb 03 '13 at 21:30