Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 20
→

Python String Formatting: f-Strings, format() & Placeholders

Python String Formatting: f-Strings, format() & Placeholders

October 17, 2026

Python String Formatting: f-Strings, format() & Placeholders

1. Introduction to Python String Formatting

String formatting is a technique used to insert variables and values into a string in a readable format. It is useful for displaying names, prices, calculations, reports, and dynamic messages.

Python supports several string formatting techniques, including:

  • F-strings

  • The format() method

  • The % formatting operator

  • Format specifiers for numbers, decimals, alignment, and padding

Example

name = "Rahul"
age = 22

print(f"My name is {name} and I am {age} years old.")

Output:

My name is Rahul and I am 22 years old.

2. Formatting Strings Using f-Strings

F-strings are a modern and readable way to insert variables and expressions into strings. They are available in Python 3.6 and later.

Place the letter f before the opening quotation mark and put variables or expressions inside curly braces {}.

Syntax

f"text {variable}"

Example 1: Display Variables

name = "Amit"
city = "Raipur"

print(f"My name is {name}. I live in {city}.")

Output:

My name is Amit. I live in Raipur.

Example 2: Evaluate Expressions

a = 10
b = 20

print(f"Sum: {a + b}")
print(f"Product: {a * b}")

Output:

Sum: 30
Product: 200

Example 3: Call Methods Inside f-Strings

name = "rahul sharma"

print(f"Student Name: {name.title()}")

Output:

Student Name: Rahul Sharma

3. Using the format() Method

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

Example 1: Basic Formatting

name = "Priya"
age = 21

message = "My name is {} and I am {} years old.".format(name, age)

print(message)

Output:

My name is Priya and I am 21 years old.

Example 2: Positional Placeholders

You can specify the position of each value.

print("{0} is learning {1}.".format("Rahul", "Python"))

Output:

Rahul is learning Python.

Example 3: Reusing a Placeholder

print("{0} loves {1}. {0} practises {1} daily.".format("Amit", "Python"))

Output:

Amit loves Python. Amit practises Python daily.

Example 4: Named Placeholders

message = "Name: {name}, Age: {age}".format(
    name="Neha",
    age=20
)

print(message)

Output:

Name: Neha, Age: 20

4. Formatting with the Percentage (%) Operator

The % operator is an older string formatting technique that you may encounter in existing Python code.

Common placeholders include:

  • %s — string representation

  • %d — integer

  • %f — floating-point number

  • %.2f — floating-point number displayed to two decimal places

Example

name = "Rahul"
age = 22
percentage = 85.567

print("Name: %s" % name)
print("Age: %d" % age)
print("Percentage: %.2f" % percentage)

Output:

Name: Rahul
Age: 22
Percentage: 85.57

For new Python code, f-strings are usually the clearest option.

5. Formatting Decimal Numbers

Use a format specifier such as :.2f to display a number with two digits after the decimal point.

Example 1: Two Decimal Places

price = 1250.5678

print(f"Price: {price:.2f}")

Output:

Price: 1250.57

Example 2: One Decimal Place

percentage = 87.456

print(f"Percentage: {percentage:.1f}%")

Output:

Percentage: 87.5%

Example 3: Thousands Separator

amount = 1250000.50

print(f"Amount: {amount:,.2f}")

Output:

Amount: 1,250,000.50

6. String Alignment and Padding

Python lets you align text within a fixed width.

Format Specifier Meaning
:<10 Left-align in a width of 10
:>10 Right-align in a width of 10
:^10 Center-align in a width of 10
:0>5 Right-align and pad with zeros

Example

name = "Python"

print(f"|{name:<10}|")
print(f"|{name:>10}|")
print(f"|{name:^10}|")

Output:

|Python    |
|    Python|
|  Python  |

Padding with Zeros

number = 42

print(f"{number:05d}")

Output:

00042

This technique is useful for invoice numbers, report columns, and formatted output.

7. Formatting Percentages

Use the % format type to display a decimal value as a percentage.

score = 0.8567

print(f"Score: {score:.2%}")

Output:

Score: 85.67%

Remember that percentage formatting multiplies the value by 100 for display.

8. Formatting Dates and Times

Python's datetime module supports formatted date and time output using strftime().

from datetime import datetime

now = datetime(2026, 10, 17, 14, 30)

print(now.strftime("%d-%m-%Y"))
print(now.strftime("%I:%M %p"))

Output:

17-10-2026
02:30 PM

Useful format codes:

  • %d — day

  • %m — month number

  • %Y — four-digit year

  • %H — hour in 24-hour format

  • %I — hour in 12-hour format

  • %M — minutes

  • %p — AM or PM

9. Practical Project: Student Report Card

This project displays student marks and percentage in a neatly formatted report.

name = input("Enter student name: ")
marks = [85, 90, 78, 92, 88]

total = sum(marks)
percentage = total / len(marks)

print("\n------ STUDENT REPORT ------")
print(f"Student Name : {name.title()}")
print(f"Total Marks  : {total}/{len(marks) * 100}")
print(f"Percentage   : {percentage:.2f}%")
print("----------------------------")

Sample Input:

Enter student name: rahul sharma

Sample Output:

------ STUDENT REPORT ------
Student Name : Rahul Sharma
Total Marks  : 433/500
Percentage   : 86.60%
----------------------------

10. Practical Project: Product Billing Receipt

Create a simple receipt using f-strings and numeric formatting.

product = "Keyboard"
quantity = 2
price = 750.50

total = quantity * price

print("\n------- BILL RECEIPT -------")
print(f"Product  : {product}")
print(f"Quantity : {quantity}")
print(f"Price    : ₹{price:,.2f}")
print(f"Total    : ₹{total:,.2f}")
print("----------------------------")

Output:

------- BILL RECEIPT -------
Product  : Keyboard
Quantity : 2
Price    : ₹750.50
Total    : ₹1,501.00
----------------------------

This example calculates the total before formatting it for display.

11. Common Mistakes in String Formatting

Mistake 1: Forgetting the f Prefix

name = "Rahul"
print("Hello, {name}")

Output:

Hello, {name}

Correct approach:

print(f"Hello, {name}")

Output: Hello, Rahul

Mistake 2: Incorrect Curly Braces

name = "Amit"
print(f"Hello, name")

Output: Hello, name

Correct approach:

print(f"Hello, {name}")

Output: Hello, Amit

Mistake 3: Using the Wrong Decimal Format

price = 99.999
print(f"{price:.2f}")

Output: 100.00

The displayed value is rounded to two decimal places.

Mistake 4: Forgetting Percentage Conversion

score = 0.85
print(f"{score:.2f}%")

Output: 0.85%

Correct approach:

print(f"{score:.0%}")

Output: 85%

12. Practice Programs

Try writing the following programs:

  1. Display a person's name and age using an f-string.

  2. Calculate two numbers and display their sum in a formatted message.

  3. Display a product price with two decimal places.

  4. Format a student's percentage with a percent sign.

  5. Print a number with leading zeros.

  6. Display text left-aligned, right-aligned, and centered.

  7. Create a simple shopping receipt.

  8. Create a student report card.

  9. Display the current date in DD-MM-YYYY format.

  10. Use format() with named placeholders.

  11. Display a large number with thousands separators.

  12. Create a neatly aligned table of products and prices.

  13. Display a calculated discount using an f-string.

  14. Format hours and minutes in a readable message.

  15. Build a formatted employee salary slip.

13. Quiz: Test Your Knowledge

Q1. What is string formatting?

Answer: It is a way to insert values into text in a readable format.

Q2. Which prefix is used for an f-string?

Answer: The letter f before the string quotation mark.

Q3. What does :.2f mean?

Answer: Display a floating-point number with two digits after the decimal point.

Q4. Which method uses {} placeholders?

Answer: The format() method.

Q5. What does :>10 do?

Answer: Right-aligns content in a field of width 10.

Q6. How can you display a decimal as a percentage?

Answer: Use the % format type, such as f"{0.85:.0%}".

Q7. Which method formats a datetime object as text?

Answer: strftime().

14. Assignment

Build a Formatted Employee Salary Slip program that:

  1. Accepts an employee's name and department.

  2. Stores the basic salary.

  3. Calculates allowances and deductions.

  4. Calculates the final salary.

  5. Displays all monetary values with two decimal places and thousands separators.

  6. Aligns labels neatly.

  7. Displays the salary month and year.

  8. Uses f-strings for the final report.

15. Summary

In this tutorial, you learned:

  • String formatting and placeholders.

  • F-strings and expression formatting.

  • The format() method and named placeholders.

  • The % formatting operator.

  • Decimal precision and thousands separators.

  • Text alignment and zero padding.

  • Percentage formatting.

  • Date and time formatting with strftime().

  • Practical projects, common mistakes, and practice programs.

Conclusion: String formatting helps Python developers create readable reports, receipts, messages, and user-friendly output. F-strings are a great default choice for most new Python programs.

←
Post 9 of 20
→