Saturday, July 2, 2022

Python - String formatting

price = 49
txt = "The price is {} dollars"
# The price is 49 dollars
print(txt.format(price))

name = "Fred"

txt = "The price is {} dollars, {}."
# The price is 49 dollars, Fred.
print(txt.format(price, name))

txt = "The price is {:.2f} dollars"
#The price is 49.00 dollars
print(txt.format(price))

quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
# I want 3 pieces of item number 567 for 49.00 dollars.
print(myorder.format(quantity, itemno, price))

myorder = "I have a {carname}, it is a {model}."
# I have a Ford, it is a Mustang.
print(myorder.format(carname = "Ford", model = "Mustang"))