Format String with Single Placeholder :
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
Output :
The price is 49 dollars
Format Number with Two Decimal Places :
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price))
Output :
The price is 49.00 dollars
Format Multiple Values in String :
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output :
I want 3 pieces of item number 567 for 49.00 dollars.
Format with Index Numbers :
quantity = 3
itemno = 567
price = 49
myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output :
I want 3 pieces of item number 567 for 49.00 dollars.
Reuse Values with Index Numbers :
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Output :
His name is John. John is 36 years old.
Format String with Named Indexes :
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
Output :
I have a Ford, it is a Mustang.