Python Reference Library →

Python format() Function – Format Strings Easily

Let’s look at format() function – format strings easily

  1. Notice

    format(value, spec) produces formatted text. The format specification controls how the value is displayed.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
number = 7
print(format(number, "04d"))
Live state

Top-level scope

number→Object 1
Object 1 · int7
This step

format(value, spec) produces formatted text. The format specification controls how the value is displayed.

Picture format() function – format strings easily

format(value, spec) produces formatted text. The format specification controls how the value is displayed.

Image brief

Alt text
A diagram for Python format() Function – Format Strings Easily. Instructions: number = 7 print(format(number, "04d")). Displayed result: 0007. The final example bindings are number --> object 1 (int). object 1: 7
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python format() Function – Format Strings Easily". Teaching focus: format(value, spec) produces formatted text. The format specification controls how the value is displayed. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS number = 7 print(format(number, "04d")) | v DISPLAYED RESULT 0007 FINAL BINDINGS number --> object 1 (int) object 1: 7 Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python format() Function – Format Strings Easily. Instructions: number = 7 print(format(number, "04d")). Displayed result: 0007. The final example bindings are number --> object 1 (int). object 1: 7

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
number = 7
print(format(number, "04d"))
Live state

Top-level scope

number→Object 1
Object 1 · int7
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
0007

What do you expect this program to print?

What does this example display?

number = 7
print(format(number, "04d"))
What does this example display?
Choose one answer. You can try again.

Answer and explanation

0007

Follow the printed values in order. The output is: 0007

More examples and reference

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))

What to remember

Connect what you noticed in the example with the idea below.

Remember

format(value, spec) produces formatted text. The format specification controls how the value is displayed.

Watch out for this idea

format() changes the original number.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →