Python format()
Function
The format() function in Python lets you format strings by inserting values into placeholders. It's a clean and powerful way to build strings with variables, numbers, and text.
Syntax
string.format(value1, value2, ...)
Parameters:
value1, value2, ...
– Values (strings, numbers, etc.) to insert into the string
Returns:
- A new string with placeholders replaced by the specified values.
Basic Example
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
My name is Alice and I am 30 years old.
Using Positional Indexes
msg = "The {1} comes after the {0}.".format("first", "second")
print(msg)
The second comes after the first.
Using Named Placeholders
msg = "Hello, {name}. You have {messages} new messages."
print(msg.format(name="John", messages=5))
Hello, John. You have 5 new messages.
Formatting Numbers
price = 49.5678
print("Price: {:.2f}".format(price))
Price: 49.57
{:.2f}
means: round to 2 decimal places
Aligning Text
print("{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right"))
Left | Center | Right
Tip: Use <
for left, ^
for center, and >
for right alignment.
Use Case: Create a Report
product = "Pen"
qty = 10
unit_price = 1.5
print("Item: {}, Qty: {}, Total: ${:.2f}".format(product, qty, qty * unit_price))
Item: Pen, Qty: 10, Total: $15.00
Common Mistakes
- Using incorrect number of placeholders vs values – will raise an
IndexError
- Using invalid format specifiers like
{:abc}
Interview Tip
String formatting is frequently asked in Python coding rounds. The format()
function is a powerful alternative to string concatenation.
Summary
format()
inserts values into a string using placeholders{}
- Supports positional and named arguments
- Useful for formatting numbers, aligning text, and generating clean output
Practice Problem
Write a program to print: “Hello, my name is NAME and I scored SCORE% in Python.” using the format()
function.
name = "Rahul"
score = 93.5
print("Hello, my name is {} and I scored {}% in Python.".format(name, score))