0
0
Pythonprogramming~5 mins

Formatting using format() method in Python

Choose your learning style9 modes available
Introduction

The format() method helps you put values into strings in a neat and clear way.

When you want to create a message that includes numbers or words dynamically.
When you need to show numbers with a specific number of decimal places.
When you want to align text or numbers in columns for better readability.
When you want to build strings that combine different types of data easily.
Syntax
Python
"string with {} placeholders".format(value1, value2, ...)

Use curly braces {} as placeholders inside the string.

Values inside format() replace the placeholders in order.

Examples
Inserts the word "Alice" into the placeholder.
Python
"Hello, {}!".format("Alice")
Inserts numbers into the string to show a simple math equation.
Python
"{} + {} = {}".format(2, 3, 5)
Formats the number to show 2 decimal places, like money.
Python
"Price: ${:.2f}".format(4.5)
Aligns the text to the left in a space of 10 characters.
Python
"{:<10} is left aligned".format("Hi")
Sample Program

This program greets Bob and shows his score rounded to 1 decimal place.

Python
name = "Bob"
score = 92.456
message = "Hello, {}! Your score is {:.1f}.".format(name, score)
print(message)
OutputSuccess
Important Notes

You can use numbers inside braces like {0}, {1} to reorder values.

The format() method works with many data types like strings, numbers, and more.

Summary

The format() method inserts values into strings using {} placeholders.

You can control number formatting and text alignment with special codes inside the braces.

This method makes your messages clear and easy to read.