- Syntax
- Example 1: Formatting a Single String
- Example 2: Formatting Multiple Values
- Example 3: Using Positional Indices
- Example 4: Reusing the Same Value
- Example 5: Using Named Arguments
- Example 6: User Input
- Example 7: Formatting a Floating-Point Number
- Example 8: Formatting an Integer
- Example 9: Mixing Different Data Types
- Example 10: Checking the Result Type
- Common Mistakes
- Best Practices
- Key Points to Remember
The format() method is another way to insert values into a string.
Instead of using the % operator, the format() method uses replacement fields ({}) as placeholders. When the format() method is called, the values provided are inserted into these placeholders.
The format() method is more flexible than % formatting because it supports positional arguments, named arguments, formatting numbers, and controlling alignment.
Although f-strings are the preferred formatting method in modern Python, understanding format() is important because it is widely used in existing Python programs.
Syntax #
"string {}".format(value)
For multiple values:
"{} {}".format(value1, value2)
Components #
| Component | Description |
|---|---|
{} |
Placeholder where a value will be inserted. |
format() |
Method that replaces placeholders with actual values. |
value |
Data inserted into the placeholder. |
Example 1: Formatting a Single String #
main.py
name = "Alice"
print("Hello, {}!".format(name))
Output #
Hello, Alice!
Explanation #
{}is a placeholder.- The
format()method replaces it with the value ofname. - The formatted string is printed.
Example 2: Formatting Multiple Values #
main.py
name = "John"
age = 25
print("Name: {}, Age: {}".format(name, age))
Output #
Name: John, Age: 25
Explanation #
- The first
{}receivesname. - The second
{}receivesage. - Values are inserted in the same order they are passed to
format().
Example 3: Using Positional Indices #
main.py
print("{1} comes after {0}.".format("Python", "Java"))
Output #
Java comes after Python.
Explanation #
{0}refers to the first argument.{1}refers to the second argument.- Positional indices allow values to appear in any order.
Example 4: Reusing the Same Value #
main.py
print("{0} is easy. {0} is powerful.".format("Python"))
Output #
Python is easy. Python is powerful.
Explanation #
{0}refers to the first argument.- The same value can be reused multiple times.
- Only one argument needs to be passed.
Example 5: Using Named Arguments #
main.py
print("Name: {name}, Age: {age}".format(name="Alice", age=21))
Output #
Name: Alice, Age: 21
Explanation #
- Named placeholders improve readability.
- Each placeholder matches the corresponding named argument.
- The order of named arguments does not matter.
Example 6: User Input #
main.py
name = input("Enter your name: ")
print("Welcome, {}!".format(name))
Sample Input #
Alice
Output #
Welcome, Alice!
Explanation #
- The user enters a name.
- The entered value replaces the placeholder.
- The formatted greeting is displayed.
Example 7: Formatting a Floating-Point Number #
main.py
price = 49.9876
print("Price: {:.2f}".format(price))
Output #
Price: 49.99
Explanation #
{:.2f}formats the number with two decimal places.- Python rounds the value automatically.
- The formatted number replaces the placeholder.
Example 8: Formatting an Integer #
main.py
marks = 95
print("Marks: {}".format(marks))
Output #
Marks: 95
Explanation #
format()automatically converts integers to strings.- No explicit conversion using
str()is required.
Example 9: Mixing Different Data Types #
main.py
name = "Laptop"
quantity = 3
price = 599.99
print("Product: {}, Quantity: {}, Price: ${:.2f}".format(name, quantity, price))
Output #
Product: Laptop, Quantity: 3, Price: $599.99
Explanation #
- The first placeholder receives the product name.
- The second placeholder receives the quantity.
{:.2f}formats the price with two decimal places.- Different data types can be formatted in a single string.
Example 10: Checking the Result Type #
main.py
result = "Hello, {}!".format("Python")
print(result)
print(type(result))
Output #
Hello, Python!
<class 'str'>
Explanation #
- The
format()method creates a new formatted string. - The returned object is of type
str.
Common Mistakes #
1. Passing Too Few Arguments #
Incorrect
print("{} {}".format("Python"))
Output #
IndexError: Replacement index 1 out of range for positional args tuple
Reason
Two placeholders require two values.
Correct
print("{} {}".format("Python", "Programming"))
2. Using an Invalid Positional Index #
Incorrect
print("{2}".format("Python", "Java"))
Output #
IndexError: Replacement index 2 out of range for positional args tuple
Reason
Only indices 0 and 1 exist.
3. Misspelling a Named Argument #
Incorrect
print("{name}".format(nam="Alice"))
Output #
KeyError: 'name'
Reason
The placeholder name must match the named argument exactly.
Correct
print("{name}".format(name="Alice"))
4. Forgetting That format() Returns a New String #
Incorrect
text = "Hello, {}"
text.format("Python")
print(text)
Output #
Hello, {}
Reason
format() returns a new string.
It does not modify the original string.
Correct
text = "Hello, {}"
text = text.format("Python")
print(text)
Best Practices #
- Use descriptive placeholder names when formatting complex strings.
- Use
{:.2f}for displaying floating-point numbers with two decimal places. - Prefer named placeholders for better readability.
- Store the formatted string if it will be reused.
- Use f-strings in new Python programs, but understand
format()for compatibility with existing code.
Key Points to Remember #
- The
format()method inserts values into placeholders ({}). - Placeholders are replaced in the order values are passed.
- Positional indices allow values to be reordered.
- Named placeholders improve readability.
format()supports formatting numbers such as{:.2f}.format()returns a new string.- The returned value is of type
str.