-2

I can tell my code is wrong for a number of reasons, but here is what I currently have. RetailItem is an object that is just the three values, description, stock, and price.

This is my current attempt at modulo formatting.

print("%d. %s $%20.2f" % (count, i.description, i.price))

I am reading through this page on the modulo string formatting, but it is just telling me how to set the minimum width instead of the maximum. What I currently have is just setting the minimum width, which messes it up because the other parts of the string are at different lengths. https://realpython.com/python-modulo-string-formatting

Thank you for your help!

A project I am working on is supposed to look like this:

Menu
---------------------------------
1. Pants                     $19.99
2. Shirt                     $12.50
3. Dress                     $79.00
4. Socks                     $1.00
5. Sweater                   $49.99
6. Cancel Purchased Item

But instead, it looks like this:

Menu
---------------------------------
1. Pants $                    19.99
2. Shirt $                    12.50
3. Dress $                    79.00
4. Socks $                     1.00
5. Sweater $                    49.99
6. Cancel Purchased Item
0

3 Answers 3

0

You'll want to pad the description field to the desired length, with spaces on the right, rather than padding the price field on the left, since you want that attached to the dollar sign.

Something like this should work for you:

"%d. %-20s $%.2f"
Sign up to request clarification or add additional context in comments.

Comments

0

You can try f-string formatting instead of modulo formatting which is easier to handle with the output format you want in a more readable format. Here is a code sample:

# implement f-string formatting instead
print(f"{count}. {i.description:<20} ${i.price:.2f}")

Note here that <20 is a right align with width value is 20

Note that there has many ways to handle this, you may take an additional look at here : inserting tab in python using string format which has more than one way to do this as well.

Comments

0

You can also try to use library which will allow you to pretty print data as table. Here is a code example using the tabulate library:

items = [{"description":"Pants","price":"$19.19"},
         {"description":"Shirt","price":"$12.50"},
         {"description":"Sweater","price":"$49.99"},
         {"description":"Cancel Purchased Item"}]

print(tabulate(items, showindex="always"))
-  ---------------------  ------
0  Pants                  $19.19
1  Shirt                  $12.50
2  Sweater                $49.99
3  Cancel Purchased Item  
-  ---------------------  ------

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.