In the previous lesson, you learned how Python string methods help modify, search, and process text. Often, programs need to combine variables, numbers, and text into meaningful messages. This process is called string formatting.
String formatting allows you to insert values into strings in a clean and readable way. Instead of joining strings manually, Python provides powerful formatting techniques such as the format() method and f-Strings.
String formatting is widely used in reports, invoices, user messages, dashboards, web applications, data analysis, and automation scripts.
In this lesson, you will learn what string formatting is, why it is useful, how the format() method works, and how to use positional arguments, keyword arguments, and automatic field numbering.
After completing this lesson, you will be able to:
format() method.String formatting is the process of inserting variables, expressions, or values into a string.
Instead of writing separate print statements or manually joining strings, formatting creates readable output using placeholders.
name = "Rahul"
age = 22
print("My name is {} and I am {} years old.".format(name, age))
Output
My name is Rahul and I am 22 years old.
Without string formatting, combining text and variables can become difficult to read.
String formatting makes programs:
It is commonly used for displaying reports, invoices, account balances, student marks, and formatted messages.
Suppose you want to display a student’s details.
name = "Rahul"
marks = 95
print("Student: " + name + " Marks: " + str(marks))
Output
Student: Rahul Marks: 95
Notice that the integer must be converted into a string using str().
name = "Rahul"
marks = 95
print("Student: {} Marks: {}".format(name, marks))
Output
Student: Rahul Marks: 95
The formatted version is shorter and easier to read.
format() MethodThe format() method replaces placeholders ({}) with values.
"Text {}".format(value)
course = "Python"
print("Welcome to {}.".format(course))
Output
Welcome to Python.
You can replace multiple placeholders in the same string.
name = "Neha"
city = "Delhi"
print("{} lives in {}.".format(name, city))
Output
Neha lives in Delhi.
Placeholders can refer to values by their position.
print("{0} scored {1} marks.".format("Rahul", 88))
Output
Rahul scored 88 marks.
The number inside the braces indicates the position of the argument.
print("{1} comes after {0}.".format("Python", "Java"))
Output
Java comes after Python.
Positional indexes allow the same values to appear in different places.
You can assign names to placeholders instead of using positions.
print("Name: {name}, Age: {age}".format(name="Rahul", age=23))
Output
Name: Rahul, Age: 23
Keyword arguments improve readability, especially when many values are used.
If placeholders are empty, Python automatically fills them in order.
print("{} is learning {}.".format("Rahul", "Python"))
Output
Rahul is learning Python.
This is the most common way to use the format() method.
A positional argument can be reused multiple times.
print("{0} loves {0}.".format("Python"))
Output
Python loves Python.
The same argument appears in multiple locations.
Suppose you want to generate a student report.
student = "Amit"
course = "Data Analytics"
print("Student: {} | Course: {}".format(student, course))
Output
Student: Amit | Course: Data Analytics
This style is commonly used when generating reports and dashboards.
Consider the following program.
name = "Priya"
result = "Welcome {}!".format(name)
print(result)
Execution Steps
"Priya" in the variable name.{}.format() method replaces the placeholder with name.result.Output
Welcome Priya!
formatAlways write format(), not format.
Each placeholder must have a corresponding value.
Use consistent formatting to keep the code readable.
format() Returns a New StringThe original string remains unchanged.
For multiple variables, the format() method produces cleaner and more maintainable code.
In this section, you learned what Python string formatting is and why it is important. You compared string concatenation with the format() method, explored placeholders, positional arguments, keyword arguments, automatic field numbering, and argument reuse. You also followed the execution flow of the format() method and reviewed common beginner mistakes. In the next section, you will learn advanced formatting techniques such as number formatting, floating-point precision, currency formatting, percentage formatting, thousands separators, alignment, padding, and formatting integers for professional output.
In the previous section, you learned how to use the format() method to insert values into strings. Python also provides advanced formatting options that allow you to display numbers professionally by controlling decimal places, currency symbols, percentages, alignment, padding, and thousands separators.
These formatting techniques are widely used in financial reports, invoices, dashboards, scientific calculations, banking applications, and data analysis.
The format() method can display numbers in different formats.
number = 1250
print("Number: {}".format(number))
Output
Number: 1250
You can control the number of decimal places displayed.
{:.2f}
The .2f format displays two digits after the decimal point.
pi = 3.14159265
print("Value: {:.2f}".format(pi))
Output
Value: 3.14
price = 499.9876
print("Price: {:.3f}".format(price))
Output
Price: 499.988
The value is rounded automatically.
Currency values can be displayed with two decimal places.
amount = 2450.5
print("Amount: ₹{:.2f}".format(amount))
Output
Amount: ₹2450.50
This style is commonly used in billing and accounting applications.
Python can display decimal values as percentages.
{:.2%}
score = 0.875
print("Percentage: {:.2%}".format(score))
Output
Percentage: 87.50%
The value is multiplied by 100 and the percentage symbol is added automatically.
Large numbers become easier to read when commas are inserted.
{:,}
population = 1456789012
print("Population: {:,}".format(population))
Output
Population: 1,456,789,012
You can specify the minimum width of an integer.
number = 25
print("{:5}".format(number))
Output
25
The number is right-aligned within five spaces.
Python supports left, right, and center alignment.
| Symbol | Meaning |
|---|---|
< |
Left Alignment |
> |
Right Alignment |
^ |
Center Alignment |
text = "Python"
print("{:<15}".format(text))
Output
Python
text = "Python"
print("{:>15}".format(text))
Output
Python
text = "Python"
print("{:^15}".format(text))
Output
Python
You can fill empty spaces using any character.
text = "Python"
print("{:*^20}".format(text))
Output
*******Python*******
The asterisk (*) is used as the fill character.
number = 45
print("{:0>5}".format(number))
Output
00045
This technique is useful when formatting IDs or invoice numbers.
Multiple formatting options can be used together.
price = 12345.6789
print("₹{:>15,.2f}".format(price))
Output
₹ 12,345.68
This example combines right alignment, comma separators, and two decimal places.
Suppose you want to display a student’s marks and percentage in a formatted report.
student = "Rahul"
marks = 456
percentage = 0.9125
print("Student : {}".format(student))
print("Marks : {:,}".format(marks))
print("Percentage : {:.2%}".format(percentage))
Output
Student : Rahul
Marks : 456
Percentage : 91.25%
Consider the following program.
salary = 78500.456
result = "Salary: ₹{:.2f}".format(salary)
print(result)
Execution Steps
78500.456 in the variable salary.format() method reads the placeholder {:.2f}.result.Output
Salary: ₹78500.46
:) in Format SpecifiersFormatting options must begin after the colon inside the braces.
.2f displays two decimal places, while .3f displays three.
Width controls spacing, whereas precision controls decimal places.
The % format automatically converts a decimal value into a percentage.
Numeric format specifiers such as .2f and , should only be used with numbers.
In this section, you learned advanced Python string formatting techniques using the format() method. You explored floating-point precision, currency formatting, percentage formatting, thousands separators, alignment, padding, fill characters, integer formatting, and combining multiple formatting options. You also followed the execution flow of formatted output and reviewed common beginner mistakes. In the next section, you will learn about Python f-Strings, including their syntax, variable interpolation, expressions, number formatting, date formatting, and real-world applications for writing clean and efficient Python code.
In the previous sections, you learned how to use the format() method to create formatted strings. Beginning with Python 3.6, a newer and more readable formatting technique called f-Strings (formatted string literals) was introduced.
f-Strings allow you to insert variables and expressions directly inside a string by placing them within curly braces ({}). They are shorter, easier to read, and generally faster than the format() method.
Today, f-Strings are the preferred way of formatting strings in modern Python applications.
An f-String is a string prefixed with the letter f or F that allows variables and expressions to be embedded directly inside the string.
f"Text {variable}"
name = "Rahul"
print(f"Welcome {name}!")
Output
Welcome Rahul!
The value of name is automatically inserted into the string.
Compared with string concatenation and the format() method, f-Strings are:
You can insert one or more variables inside an f-String.
student = "Neha"
course = "Python"
print(f"{student} is learning {course}.")
Output
Neha is learning Python.
Multiple variables can be displayed in the same string.
name = "Amit"
age = 23
city = "Delhi"
print(f"Name: {name}, Age: {age}, City: {city}")
Output
Name: Amit, Age: 23, City: Delhi
One of the biggest advantages of f-Strings is that expressions can be evaluated directly inside the placeholders.
a = 15
b = 20
print(f"Sum = {a + b}")
Output
Sum = 35
number = 8
print(f"Square = {number ** 2}")
Output
Square = 64
Python evaluates the expression before displaying the result.
Formatting options used with format() also work inside f-Strings.
pi = 3.14159265
print(f"Value: {pi:.2f}")
Output
Value: 3.14
population = 1456789012
print(f"Population: {population:,}")
Output
Population: 1,456,789,012
score = 0.945
print(f"Percentage: {score:.2%}")
Output
Percentage: 94.50%
f-Strings can format currency values.
salary = 78500.456
print(f"Salary: ₹{salary:,.2f}")
Output
Salary: ₹78,500.46
You can align text inside an f-String.
text = "Python"
print(f"|{text:<15}|")
Output
|Python |
print(f"|{text:>15}|")
Output
| Python|
print(f"|{text:^15}|")
Output
| Python |
f-Strings work well with Python's datetime module.
from datetime import datetime
today = datetime.now()
print(f"Today's Date: {today:%d-%m-%Y}")
Sample Output
Today's Date: 06-08-2026
student = "Rahul"
marks = 458
percentage = 91.60
print(f"Student : {student}")
print(f"Marks : {marks}")
print(f"Percentage: {percentage:.2f}%")
Output
Student : Rahul
Marks : 458
Percentage: 91.60%
product = "Laptop"
price = 65999.5
print(f"Product : {product}")
print(f"Price : ₹{price:,.2f}")
Output
Product : Laptop
Price : ₹65,999.50
Consider the following program.
name = "Priya"
age = 24
message = f"{name} is {age} years old."
print(message)
Execution Steps
name and age.f.Output
Priya is 24 years old.
They are more readable and generally faster than older formatting methods.
Avoid placing very complex expressions inside the placeholders.
Apply precision, alignment, and separators for professional output.
Descriptive variable names improve readability inside f-Strings.
They make generated reports, invoices, and user messages much easier to read.
f prefix before the string.In this section, you learned how Python f-Strings simplify string formatting by allowing variables and expressions to be embedded directly inside strings. You explored basic syntax, variable interpolation, arithmetic expressions, number formatting, currency formatting, percentage formatting, alignment, and date formatting. You also applied f-Strings to practical examples such as student reports and invoices, followed the execution flow of formatted strings, and reviewed best practices and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Escape Characters & String Operations.
In this lesson, you learned how Python string formatting makes it easy to combine text with variables, numbers, and expressions to produce clear and professional output. Instead of relying on string concatenation, you explored modern formatting techniques using the format() method and f-Strings.
You began by understanding the purpose of string formatting and learned how placeholders work with the format() method. You practiced using positional arguments, keyword arguments, automatic field numbering, and reusing arguments to create readable output.
You then explored advanced formatting features such as controlling decimal precision, formatting currency values, displaying percentages, adding thousands separators, aligning text, and applying padding with fill characters. Finally, you learned how to use Python f-Strings, which provide a faster, cleaner, and more readable way to embed variables and expressions directly into strings.
These formatting techniques are essential for creating reports, invoices, dashboards, financial summaries, scientific calculations, and user-friendly applications.
format() method uses placeholders {} to replace values..2f formats floating-point numbers with two decimal places..2% converts decimal values into percentages., adds thousands separators to large numbers.<, >, ^) control text placement.String formatting is the process of inserting variables, expressions, or values into a string.
Concatenation joins strings manually, while string formatting inserts values into placeholders, producing cleaner and more readable code.
format() method?The format() method replaces placeholders in a string with supplied values.
Positional arguments identify values using numeric indexes inside placeholders.
Keyword arguments assign names to placeholders, improving readability.
f-Strings are formatted string literals that allow variables and expressions to be embedded directly inside a string using curly braces.
Use the format specifier .2f.
Use the format specifier .2% to display a decimal value as a percentage.
Use the comma format specifier ,.
f-Strings are recommended because they are shorter, easier to read, and generally faster than older formatting methods.
format() method.format() method.format() method work?Create a Python program that generates a professionally formatted report card using both the format() method and f-Strings.
Your program should:
========================================
STUDENT REPORT CARD
========================================
Name : Rahul Sharma
Roll Number : 101
Course : Python Programming
Marks : 458
Percentage : 91.60%
Status : PASS
========================================
Generated On : 06-08-2026
========================================
Congratulations! You have successfully learned Python String Formatting. You now understand how to use the format() method, positional and keyword arguments, floating-point precision, currency formatting, percentage formatting, thousands separators, alignment, padding, and modern f-Strings to produce clean and professional output.
In the next lesson, you will learn Python Escape Characters & String Operations: Complete Guide for Beginners. You will explore escape characters such as \n, \t, \\, \', and \", raw strings, string concatenation, repetition, membership operators, string comparison, Unicode strings, and practical text-processing operations.