Home > front end >  Attempting to add '$' before number
Attempting to add '$' before number

Time:08-20

Need a bit of help adding $ right before each number is printed while also keeping the whole text centered, as of now the $ gets pushed a bit further away then the price does cause of the {:10}.

I'm just starting so maybe there is an easy fix but I've attempted to use the .join method as well only for the whole text to be replaced with $, also using f-strings although I doubt that would make that much of an difference in me finding a solution. Had to write this cause it made me add more details to this.

def centered_text(text: str = " ", width: int = 50) -> None:
    """
    text: Text we want to print out
    width: Max characters text can be
    return: Return text centered
    """
    if len(text) > width - 4:
        print("Invalid choice, you put {} characters".format((len(text) - width)))
    if text == "*":
        print("*" * width)
    else:
        centered = text.center(width - 4)
        output_sting = "**{}**".format(centered)
        print(output_sting)


cart = []
special_items = {'Metal pipe': 5.99,
                 'Large table': 30.99,
                 'Battle ship': 12.99,
                 'Gaming PC': 1599.99,
                 '24-Pack of water': 19.99,
                 'Dog chew toy': 4.99,
                 'Space Ice cream': 8.99,
                 'Nerf gun': 10.99,
                 'Pokemon cards': 6.99,
                 'Desk': 49.99}

print("Welcome to Amazon, we have some special offers for you! Please enjoy these offers from the list below!")

centered_text("*")
for item, price in special_items.items():
    x = "{:20} ${:10}".format(item, price)
    centered_text(x)

centered_text("*")

Output should be something like this:

**************************************************
**       Metal pipe                 $5.99       **
**       Large table               $30.99       **
**       Battle ship               $12.99       **
**       Gaming PC               $1599.99       **
**       24-Pack of water          $19.99       **
**       Dog chew toy               $4.99       **
**       Space Ice cream            $8.99       **
**       Nerf gun                  $10.99       **
**       Pokemon cards              $6.99       **
**       Desk                      $49.99       **
**************************************************

CodePudding user response:

You need to add the $ sign as part of the object being formatted.

for item, price in special_items.items():
    x = "{:20} {:>10}".format(item, f"${price}")
    centered_text(x)

Here I just changed price to f"${price}". That > in {:>10} is for right alignment.

To be consistent in two decimal digit you can use f"${price:.2f}

CodePudding user response:

Since you want the dollar-sign prefix to right justify with the rest of the price, you probably need to do the formatting in two steps:

x = "{:20} {:>10}".format(item, "${}".format(price))
  • Related