Home Course Roadmap
Lesson 18 · Strings

Python f-Strings

Learn how to build clean, readable, and dynamic text using Python f-strings. You'll work with variables, expressions, functions, numbers, percentages, alignment, formatting, and real-world output.

40–50 minutes
Beginner
Python Foundations
0%

By the end of this lesson, you will be able to:

  • Understand what f-strings are and why they are useful.
  • Insert variables directly into strings.
  • Place expressions inside f-strings.
  • Call functions inside formatted strings.
  • Control decimal places and numeric formatting.
  • Format percentages and large numbers.
  • Align and pad text.
  • Use the debugging = feature.
  • Avoid common f-string errors.
01

What Are f-Strings?

An f-string is a Python string that allows you to insert variables and expressions directly inside the string.

The letter f is placed before the opening quotation mark.

Basic example
name = "Adnan"

message = f"Hello, {name}!"

print(message)
Output
Hello, Adnan!
Core idea

Anything inside { } in an f-string can be evaluated by Python and inserted into the resulting text.

02

Why Use f-Strings?

Before f-strings, programmers commonly used concatenation or older formatting techniques.

Concatenation

Older approach
name = "Adnan"
age = 30

message = "My name is " + name + " and I am " + str(age) + " years old."

print(message)

Using an f-string

Modern approach
name = "Adnan"
age = 30

message = f"My name is {name} and I am {age} years old."

print(message)
Why f-strings are popular

They are concise, readable, expressive, and make it easy to combine text with variables and calculations.

03

Basic f-String Syntax

The general structure is:

Syntax
f"text {expression} text"

For example:

Example
name = "Sara"

print(f"Welcome, {name}!")
Output
Welcome, Sara!
04

Using Variables

You can insert variables of different data types directly into an f-string.

Different data types
name = "Ali"
age = 25
height = 5.9
student = True

print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}")
print(f"Student: {student}")
Output
Name: Ali
Age: 25
Height: 5.9
Student: True

Python automatically converts the values into their string representation for the formatted output.

05

Using Multiple Values

An f-string can contain as many replacement fields as your output requires.

Example
product = "Laptop"
price = 85000
quantity = 2

print(f"Product: {product}")
print(f"Price: Rs. {price}")
print(f"Quantity: {quantity}")
print(f"Total: Rs. {price * quantity}")
Output
Product: Laptop
Price: Rs. 85000
Quantity: 2
Total: Rs. 170000
06

Using Expressions Inside f-Strings

One of the most powerful features of f-strings is that you can place Python expressions inside the braces.

Arithmetic expression
a = 10
b = 5

print(f"Sum: {a + b}")
print(f"Difference: {a - b}")
print(f"Product: {a * b}")
print(f"Division: {a / b}")
Output
Sum: 15
Difference: 5
Product: 50
Division: 2.0

You can also use comparisons and conditional expressions.

Conditional expression
age = 20

print(f"Status: {'Adult' if age >= 18 else 'Minor'}")
Output
Status: Adult
07

Calling Functions Inside f-Strings

You can call functions inside replacement fields.

Example
name = "python"

print(f"Language: {name.title()}")
print(f"Length: {len(name)}")
Output
Language: Python
Length: 6

This becomes especially useful when formatting data before displaying it to users.

08

Format Specifiers

f-strings allow you to control how values are displayed using a format specifier.

Syntax
f"{value:format_specifier}"

The colon separates the expression from its formatting instructions.

Simple example
price = 1250.5678

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

Formatting Decimal Numbers

Use .2f when you want a number displayed with exactly two digits after the decimal point.

Decimal formatting
price = 1999.5
tax = 347.2567

print(f"Price: {price:.2f}")
print(f"Tax: {tax:.2f}")
Output
Price: 1999.50
Tax: 347.26

The number after the decimal specifies how many decimal places should be displayed.

Different precision
number = 12.3456789

print(f"{number:.1f}")
print(f"{number:.2f}")
print(f"{number:.3f}")
Output
12.3
12.35
12.346
10

Thousands Separators

Large numbers can be made easier to read using the comma formatting option.

Example
population = 240000000

print(f"Population: {population:,}")
Output
Population: 240,000,000

This is especially useful for reports, financial dashboards, sales systems, and business applications.

11

Formatting Percentages

The % format specifier converts a decimal value into a percentage representation.

Example
completion = 0.875

print(f"Course completion: {completion:.1%}")
Output
Course completion: 87.5%

The original value is 0.875, but Python displays it as 87.5%.

12

Text Alignment

f-strings can align text to the left, right, or center.

Alignment
name = "Python"

print(f"{name:<15}")
print(f"{name:>15}")
print(f"{name:^15}")
Output
Python         
         Python
    Python     

The symbols mean:

  • < — left aligned
  • > — right aligned
  • ^ — centered
13

Width & Padding

You can specify a minimum field width when formatting values.

Example
item = "Laptop"
price = 85000

print(f"{item:<15} {price:>10,}")
Output
Laptop             85,000

This technique can be useful when creating simple text-based tables and reports.

14

Debugging with the = Feature

Modern Python versions provide a convenient f-string debugging feature using =.

Debugging example
name = "Ali"
age = 25

print(f"{name=}")
print(f"{age=}")
print(f"{age + 5=}")
Output
name='Ali'
age=25
age + 5=30
Developer tip

This is extremely useful while debugging because it displays both the expression and its resulting value.

15

Quotes & Curly Braces

Sometimes your text needs quotation marks or literal curly braces.

Using Quotes

Example
name = "Ali"

print(f'{name} said "Hello!"')
Output
Ali said "Hello!"

Displaying Literal Curly Braces

Curly braces normally represent replacement fields. To display actual braces, use double braces.

Literal braces
name = "Python"

print(f"{{{name}}}")
Output
{Python}
16

Practical Real-World Examples

Example 1 — Student Result

Student result
name = "Sara"
marks = 87
total = 100

percentage = marks / total

print(f"Student: {name}")
print(f"Marks: {marks}/{total}")
print(f"Percentage: {percentage:.1%}")
Output
Student: Sara
Marks: 87/100
Percentage: 87.0%

Example 2 — Shopping Bill

Shopping bill
item = "Keyboard"
price = 3500
quantity = 2

subtotal = price * quantity
tax = subtotal * 0.05
total = subtotal + tax

print(f"Item: {item}")
print(f"Quantity: {quantity}")
print(f"Subtotal: Rs. {subtotal:,}")
print(f"Tax: Rs. {tax:,.2f}")
print(f"Total: Rs. {total:,.2f}")
Output
Item: Keyboard
Quantity: 2
Subtotal: Rs. 7,000
Tax: Rs. 350.00
Total: Rs. 7,350.00

Example 3 — User Profile

Profile display
name = "Muhammad Adnan"
age = 30
city = "Multan"
profession = "Python Learner"

profile = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"City: {city}\n"
    f"Profession: {profession}"
)

print(profile)
Output
Name: Muhammad Adnan
Age: 30
City: Multan
Profession: Python Learner

Example 4 — Simple Sales Report

Business report
sales = 1250000
growth = 0.184

print(f"Monthly Sales: Rs. {sales:,}")
print(f"Growth Rate: {growth:.1%}")
Output
Monthly Sales: Rs. 1,250,000
Growth Rate: 18.4%
17

Common f-String Mistakes

Mistake 1 — Forgetting the f

Writing "Hello {name}" without the f produces literal braces instead of substituting the variable.

Mistake 2 — Using incorrect braces

Variables and expressions must be placed inside { }.

Mistake 3 — Confusing formatting syntax

For example, use {price:.2f} for two decimal places, not {price:2f}.

Mistake 4 — Expecting formatting to change the value

Formatting controls how the value is displayed. It does not permanently change the original numeric variable.

18

Practice Exercises

Try these exercises yourself before looking for solutions.

Exercise 1 — Personal Greeting

Create variables for a person's name and city, then display a sentence using an f-string.

Exercise 2 — Calculate Total

Given a price and quantity, calculate the total and display it using an f-string.

Exercise 3 — Decimal Formatting

Display 123.456789 with exactly two decimal places.

Exercise 4 — Percentage

Format 0.9235 as a percentage with two decimal places.

Exercise 5 — Large Number

Display 9876543210 with thousands separators.

Exercise 6 — Text Formatting

Create a simple two-column product display using text alignment.

Exercise 7 — Debugging

Use the f-string = feature to display both a variable and its value.

19

Mini Challenge — Professional Invoice

Build a small invoice generator using f-strings.

Your program should:

  • Store a customer name.
  • Store product name, price, and quantity.
  • Calculate the subtotal.
  • Calculate a 5% tax.
  • Calculate the final total.
  • Format large numbers with commas.
  • Display monetary values with two decimal places.
  • Produce a clean invoice using f-strings.
Challenge Starter
customer = "Ali"
product = "Wireless Mouse"
price = 2500
quantity = 3

subtotal = ...
tax_rate = ...
tax = ...
total = ...

print("=" * 40)
print(f"Customer: {customer}")
print(f"Product:  {product}")
print(f"Quantity: {quantity}")
print(f"Price:    Rs. {price:,.2f}")
print(f"Subtotal: Rs. {subtotal:,.2f}")
print(f"Tax:      Rs. {tax:,.2f}")
print(f"Total:    Rs. {total:,.2f}")
print("=" * 40)
Challenge Goal

Make your output look like a real invoice. Focus on both correct calculations and professional formatting.

20

Quick Knowledge Check

1. What character is placed before the string to create an f-string?

2. Where are variables placed inside an f-string?

3. What does f"{price:.2f}" do?

4. What does {number:,} do?

5. What does {value:.1%} do?

6. Can Python evaluate expressions inside an f-string?

7. What does {name=} help with?

8. How do you display literal curly braces inside an f-string?

21

Lesson Summary

f-strings are one of the most useful and readable ways to create dynamic text in modern Python.

  • An f-string begins with f before the opening quotation mark.
  • Variables and expressions are placed inside { }.
  • f-strings can evaluate arithmetic and other Python expressions.
  • Functions can be called inside replacement fields.
  • Format specifiers control how values are displayed.
  • :.2f displays two decimal places.
  • , adds thousands separators.
  • :.1% displays a percentage with one decimal place.
  • <, >, and ^ control text alignment.
  • {variable=} is useful for debugging.
  • Double curly braces can display literal curly braces.
Key takeaway

f-strings turn Python output from simple text into dynamic, readable, professional information. They are an essential skill for scripts, applications, reports, dashboards, and real-world software.

Excellent work!

You have completed Python f-Strings. Practice creating formatted output and experiment with different format specifiers before moving to the next lesson.