Python String Formatting
We can format the results using the format()
method to ensure that a string is presented as expected.
String format()
You can format chosen elements of a string using the format()
method.
Sometimes you do not control sections of a text, perhaps it comes from a database or user input?
Add placeholders (curly brackets {}
) in the text, and execute values via the format()
method for controlling such values:
Example 1 :- Indicate the price by adding a placeholder :
price = 49
txt = "The price is {} dollars"
print(txt.format(price))
Output :-
Within the curly brackets, you can add specifications for how the value can be converted.
Example 2 :- The pricing format to be shown as a two decimal number :
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price))
Output :-
In our string format()
references, check all formatting types.
Multiple Values
If you wish to use more values, simply add more values to the method of format()
:
print(txt.format(price, itemno, count))
Example :- Add more placeholders :
quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
Output :-
Related Links
Index Numbers
Example 1 :- You can use index numbers (a number inside the curly brackets {0}
) to be sure the values are placed in the correct placeholders :
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 :-
Example 2 :- Also, use an index number if you would like to refer to the same data more than once :
age = 36
name = "John"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))
Output :-
Related Links
Named Indexes
Example :- In the curly bracket {carname}
, the named indexes can be used too, however when you supply the values of parameter txt.format(carname="Ford")
you must use names :
myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Ford", model = "Mustang"))
Output :-