Python String Formatting


To ensure that the character unit will appear as expected, we can format the result with the format() method.


String format()

Format() method allows you to format selected parts of a character unit.

Sometimes there are parts of the text that you do not control, perhaps from a website, or a user input?

To control such values, add pronouns (twisted brackets {}) to the text, and use values ​​in the format():


Example

Add a placeholder where you want to display the price:

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

You can add parameters within the folded brackets to specify how to convert a value:


Example

Format the price to be displayed as a number with two decimals:

txt = "The price is {:.2f} dollars"


Multiple Values

If you want to use additional values, just add additional values ​​to the format ():


print(txt.format(price, itemno, count))

Also add additional placeholders:


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


Index Numbers

You can use index numbers (numbers in parentheses {0}) to make sure values ​​are set in the correct denominators:


Example
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))

Also, if you want to refer to the same number more than once, use the reference number:


Example
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))


Named Indexes

You can also use fictional expressions by inserting a word inside italics {carname}, but you must use words when exceeding the parameters values ​​txt.format (carname = "Ford"):


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