Python Tutorials
- Python
- How to install Python?
- PIP
- How to Run Python Program
- Python Identifiers,Statement, Indentation and Comments
- Variable
- Data type
- Decision Making
- Python Loops
- Break,Continue, Pass
- Functions
- Predefine Functions
- Lambda Functions
- Variable Scope
- List
- Tuple
- Python Sets
- Python Dictionary
- Python String
- String Formating
- Input/Output
- File Handling (Input / Output)
- Iterators
- Python Modules
- Python Date
- Python JSON
- Classes and Objects
- Constructor
- Polymorphism
- Encapsulation
- inheritance
- Class or Static Variables in Python
- class method vs static method
- Abstraction
- Exception Handling
- MySql Python
- MySql Create Database
- MySql CRUD
- Django
What is String Formating in Python?
string will display as expected, we can format the result with the format() method.
The format() method allows you 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:
File name : index.py
price = 50
txt = "The price is {} Rupies"
print(txt.format(price))
Output :
The price is 50 Rupies
Example
Format the price to be displayed as a number with two decimals:
File name : index.py
price = 50
txt = "The price is {:.2f} Rupies"
print(txt.format(price))
Output :
The price is 50.00 Rupies
Multiple Values
File name : index.py
quantity = 2
itemno = 500
price = 50
myorder = "I want {} pieces of item number {} for {:.2f} Rupies."
print(myorder.format(quantity, itemno, price))
Output :-
I want 2 pieces of item number 500 for 50.00 Rupies.
File name : index.py
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.