I'm new to Python and trying to work on some sample scripts. I'm doing a simple a cash-register type thing but I want to justify or right align the output so that it looks something like this:
subTotal = 24.95
tax = subTotal * 0.0725
total = subTotal + tax
paid = 30
change = paid-total
print("The subtotal was: $",subTotal)
print("The tax was: $",tax)
print("The total was: $",total)
print("The customer paid: $",paid)
print("Change due: $",change)
I know I could simplify this with a lot less print statements, but I just wanted it to be easier to see what I'm trying to do.
I want it to output something like this, notice that the dollar amounts are all aligned and that there is no space between the $ and the dollar amount. I do not know how to do these two things.
The subtotal was: $24.95
The tax was: $1.81
The total was: $26.76
The customer paid: $30.00
Change due: $3.24
I tried reading the Python docs for the format method, but I didn't see any examples as to what format specifiers can be used to do certain things. Thanks in advance for any help.
You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
Format Function in Python (str. format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format.
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
The amount can be formated like this:
"${:.2f}".format(amount)
You can add padding to a string, for example for a width of 20:
"{:20s}".format(mystring)
You can right align the string, for example with a width of 7:
"{:>7s}".format(mystring)
Putting all this together:
s = "The subtotal was:"
a = 24.95
print("{:20s}{:>7s}".format(s, "${.2f}".format(a))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With