WHAT IS THE STRING FORMATTING IN PYTHON?

STRING FORMATTING

format() method in python is used to format the selected parts of a string by placing the curly braces {} as placeholder on the selected part of string, which we want to get filled by values provided from user input or database, and running the values through format() method.

Example- Add a placeholder/{} where we want to display the value as shown below-

col="red"
weight = 40
st = "The weight of bag is {} KG"
print(st.format(weight))

#parameter passed in {}
st = "The weight of bag is {:.2f} KG" 
print(st.format(weight))

#Multiple Parameters passed & index of values provided in {}
st = "The weight of {0} nos. {1} colored bags is {2:.2f} KG" 
print(st.format(2, col, weight))

#Named indexes passed by entering a name inside the {}
#Values to be provided to parameteres passed in format()
st = "The weight of {no} nos. {col} colored bags is {weight} KG" 
print(st.format(no=2, col="red", weight=40))

Output

The weight of bag is 40 KG
The weight of bag is 40.00 KG
The weight of 2 nos. red colored bags is 40.00 KG
The weight of 2 nos. red colored bags is 40 KG

Posted

in

Tags:

Comments

Leave a Reply