Welcome Friends!
Let's see more in the formatting of strings today.
There are various ways in which we can format the text being displayed using the print statement.
For example, if we want to print the price of flowers as $3.50.
item_name = "flower"
item_price = 3.5
item_name = "flower" item_price = 3.5 print("1. Price for", item_name, "is $", item_price) print("2. Price for " + item_name + " is $" + str(item_price)) print("3. Price for {} is ${}".format(item_name , item_price)) print(f"4. Price for {item_name} is ${item_price}")
If we run this, we will see our output as:
1. Price for flower is $ 3.5 2. Price for flower is $3.5 3. Price for flower is $3.5 4. Price for flower is $3.5
You can use whichever option you like or can remember it. The item price doesn't look quite right. We now need to round this to 2 decimal places. Let's try it out.
item_name = "flower" item_price = 3.5 print("1. Price for", item_name, "is $", "{:.2f}".format(item_price)) print("2. Price for " + item_name + " is $" + "{:.2f}".format(item_price)) print("3. Price for {} is ${:.2f}".format(item_name, item_price)) print(f"4. Price for {item_name} is ${item_price:.2f}")
And the result for this will be:
1. Price for flower is $ 3.50 2. Price for flower is $3.50 3. Price for flower is $3.50 4. Price for flower is $3.50
Let's take another example of formatting. In this case, I will use option 3 but you can use any of the options and it will work the same way.
name = "Learning Python" date = "05-Jan-2020" item_name_1 = "Flowers" item_name_2 = "Cake" item_price_1 = 33.50 item_price_2 = 9.99 tax = .05 * (item_price_1 + item_price_2) total = tax + item_price_1 + item_price_2 print("{:>30}: {:<25}".format("Name", name)) print("{:>30}: {:<25}".format("Purchase Date", date)) print("{:>30}: ${:>6.2f}".format(item_name_1, item_price_1)) print("{:>30}: ${:>6.2f}".format(item_name_2, item_price_2)) print("{:>30}: ${:>6.2f}".format("Tax (5%)", tax)) print("{:>30}: ${:>6.2f}".format("Total Price(including 5% tax)", total))
Let's see its output.
Name: Learning Python Purchase Date: 05-Jan-2020 Flowers: $ 33.50 Cake: $ 9.99 Tax (5%): $ 2.17 Total Price(including 5% tax): $ 45.66
I hope you have enjoyed this. In our next post, we will discuss functions. Stay tuned.
No comments:
Post a Comment