Python - String Formatting
To make sure a string will display as expected, we can format the result with the format() method.
The format() method allows us to format selected parts of a string.
Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?
To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method:
Add a placeholder where you want to display the price:
price = 56
txt = "The price is {} dollars"
print(txt.format(price))
======o/p======
The price is 56 dollars
Add a placeholder where you want to display the object:
object = "cooler"
txt=("the object is {}")
print(txt.format(object))
=======o/p======
the object is cooler
You can add parameters inside the curly brackets to specify how to convert the value:
Format the price to be displayed as a number with two decimals:
price = 95
txt = "The price is {:.2f} dollars"
print(txt.format(price))
=======o/p=======
The price is 95.00 dollars
If you want to use more values, just add more values to the format() method.
print(txt.format(brand,object,price))
And add more placeholders:
brand="Magnum"
object="Ice cream"
price=250
txt =("i want {} {} of {} rupees")
print(txt.format(brand,object,price))
=========o/p==========
i want Magnum Ice cream of 250 rupees
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
price=256
itemnumber = 58
myorder="i want {0} pieces of itemnumber {2} at {1} rupees"
print(myorder.format(quantity,price,itemnumber))
=========o/p==========
i want 3 pieces of itemnumber 58 at 256 rupees
Also, if you want to refer to the same value more than once, use the index number:
name = "freedom tutorials"
year = 2018
object="famous"
myword="{0} was started in {1}.{0} is {2}"
print(myword.format(name,year,object))
========o/p=========
freedom tutorials was started in 2018.freedom tutorials is famous
You can also use named indexes by entering a name inside the curly brackets, but then you must use names when you pass the parameter values.
Example :txt.format(mobilename = "VIVO")
myorder="I have {mobilename},it is {model} and of price {cost}"
print(myorder.format(mobilename="VIVO" ,model="Ypro",cost=15000))
=========o/p==========
I have VIVO,it is Ypro and of price 15000