Search code examples
pythonstring-formatting

String Formatting Dollar Sign In Python


So I'm trying to get the dollar sign to appear directly to the left of the digits under the column 'Cost'. I'm having trouble figuring this out and any help is appreciated.

# Question 5

print("\nQuestion 5.")

# Get amount of each type of ticket to be purchased

adultTickets = input("\nHow many adult tickets you want to order: ")

adultCost = int(adultTickets) * 50.5

childTickets = input("How many children (>=10 years old) tickets: ")

childCost = int(childTickets) * 10.5

youngChildTickets = input("How many children (<10 years old) tickets: ")

# Display ticket info

print ("\n{0:<17} {1:>17} {2:>12}".format("Type", "Number of tickets", 
"Cost"))

print ("{0:<17} {1:>17}${2:>12.2f}".format("Adult", adultTickets, adultCost))

print ("{0:<17} {1:>17}${2:>12.2f}".format("Children (>=10)", childTickets, 
childCost))

print ("{0:<17} {1:>17} {2:>12}".format("Children (<10)", youngChildTickets, 
"free"))

#Calculate total cost and total amount of tickets

totalTickets = (int(adultTickets) + int(childTickets) + 
int(youngChildTickets))

totalCost = adultCost + childCost

print ("{0:<17} {1:>17}${2:>12.2f}".format("Total", totalTickets, totalCost))

I also want the cost column to be formatted right, which for some reason it isn't when I run the program.

(My output):

enter image description here Edit: I also can't format the '$' onto the cost, as I have to keep the 2 decimal places in the formatting


Solution

  • If I understand correctly, you want to format a floating point number into a string, and have a dollar sign appear in the output in between the number and the padding that you use to space it out in the string. For example, you want to be able to create these two strings with the same formatting code (just different values):

    foo:    $1.23
    foo:   $12.34
    

    Unfortunately, you can't do this with just one string formatting operation. When you apply padding to a number, the padding characters will appear in between the number and any prefixing text, like the dollar signs in your current code. You probably need to format the number in two steps. First make the numbers into strings prefixed with the dollar signs, then format again to insert the dollar strings into the final string with the appropriate padding.

    Here's how I'd produce the example strings above:

    a = 1.23
    b = 12.34
    
    a_dollars = "${:.2f}".format(a)  # make strings with leading dollar sign
    b_dollars = "${:.2f}".format(b)
    
    a_padded = "foo:{:>8}".format(a_dollars)  # insert them into strings with padding
    b_padded = "foo:{:>8}".format(b_dollars)