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.
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.
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.
name = "Adnan"
message = f"Hello, {name}!"
print(message)
Hello, Adnan!
Anything inside { } in an f-string
can be evaluated by Python and inserted into
the resulting text.
Why Use f-Strings?
Before f-strings, programmers commonly used concatenation or older formatting techniques.
Concatenation
name = "Adnan"
age = 30
message = "My name is " + name + " and I am " + str(age) + " years old."
print(message)
Using an f-string
name = "Adnan"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message)
They are concise, readable, expressive, and make it easy to combine text with variables and calculations.
Basic f-String Syntax
The general structure is:
f"text {expression} text"
For example:
name = "Sara"
print(f"Welcome, {name}!")
Welcome, Sara!
Using Variables
You can insert variables of different data types directly into an f-string.
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}")
Name: Ali Age: 25 Height: 5.9 Student: True
Python automatically converts the values into their string representation for the formatted output.
Using Multiple Values
An f-string can contain as many replacement fields as your output requires.
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}")
Product: Laptop Price: Rs. 85000 Quantity: 2 Total: Rs. 170000
Using Expressions Inside f-Strings
One of the most powerful features of f-strings is that you can place Python expressions inside the braces.
a = 10
b = 5
print(f"Sum: {a + b}")
print(f"Difference: {a - b}")
print(f"Product: {a * b}")
print(f"Division: {a / b}")
Sum: 15 Difference: 5 Product: 50 Division: 2.0
You can also use comparisons and conditional expressions.
age = 20
print(f"Status: {'Adult' if age >= 18 else 'Minor'}")
Status: Adult
Calling Functions Inside f-Strings
You can call functions inside replacement fields.
name = "python"
print(f"Language: {name.title()}")
print(f"Length: {len(name)}")
Language: Python Length: 6
This becomes especially useful when formatting data before displaying it to users.
Format Specifiers
f-strings allow you to control how values are displayed using a format specifier.
f"{value:format_specifier}"
The colon separates the expression from its formatting instructions.
price = 1250.5678
print(f"Price: {price:.2f}")
Price: 1250.57
Formatting Decimal Numbers
Use .2f when you want a number displayed
with exactly two digits after the decimal point.
price = 1999.5
tax = 347.2567
print(f"Price: {price:.2f}")
print(f"Tax: {tax:.2f}")
Price: 1999.50 Tax: 347.26
The number after the decimal specifies how many decimal places should be displayed.
number = 12.3456789
print(f"{number:.1f}")
print(f"{number:.2f}")
print(f"{number:.3f}")
12.3 12.35 12.346
Thousands Separators
Large numbers can be made easier to read using the comma formatting option.
population = 240000000
print(f"Population: {population:,}")
Population: 240,000,000
This is especially useful for reports, financial dashboards, sales systems, and business applications.
Formatting Percentages
The % format specifier converts a decimal
value into a percentage representation.
completion = 0.875
print(f"Course completion: {completion:.1%}")
Course completion: 87.5%
The original value is 0.875, but Python
displays it as 87.5%.
Text Alignment
f-strings can align text to the left, right, or center.
name = "Python"
print(f"{name:<15}")
print(f"{name:>15}")
print(f"{name:^15}")
Python
Python
Python
The symbols mean:
-
<— left aligned -
>— right aligned -
^— centered
Width & Padding
You can specify a minimum field width when formatting values.
item = "Laptop"
price = 85000
print(f"{item:<15} {price:>10,}")
Laptop 85,000
This technique can be useful when creating simple text-based tables and reports.
Debugging with the = Feature
Modern Python versions provide a convenient f-string
debugging feature using =.
name = "Ali"
age = 25
print(f"{name=}")
print(f"{age=}")
print(f"{age + 5=}")
name='Ali' age=25 age + 5=30
This is extremely useful while debugging because it displays both the expression and its resulting value.
Quotes & Curly Braces
Sometimes your text needs quotation marks or literal curly braces.
Using Quotes
name = "Ali"
print(f'{name} said "Hello!"')
Ali said "Hello!"
Displaying Literal Curly Braces
Curly braces normally represent replacement fields. To display actual braces, use double braces.
name = "Python"
print(f"{{{name}}}")
{Python}
Practical Real-World Examples
Example 1 — 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%}")
Student: Sara Marks: 87/100 Percentage: 87.0%
Example 2 — 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}")
Item: Keyboard Quantity: 2 Subtotal: Rs. 7,000 Tax: Rs. 350.00 Total: Rs. 7,350.00
Example 3 — User Profile
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)
Name: Muhammad Adnan Age: 30 City: Multan Profession: Python Learner
Example 4 — Simple Sales Report
sales = 1250000
growth = 0.184
print(f"Monthly Sales: Rs. {sales:,}")
print(f"Growth Rate: {growth:.1%}")
Monthly Sales: Rs. 1,250,000 Growth Rate: 18.4%
Common f-String Mistakes
Writing "Hello {name}" without
the f produces literal braces
instead of substituting the variable.
Variables and expressions must be placed
inside { }.
For example, use {price:.2f}
for two decimal places, not
{price:2f}.
Formatting controls how the value is displayed. It does not permanently change the original numeric variable.
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.
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.
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)
Make your output look like a real invoice. Focus on both correct calculations and professional formatting.
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?
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
fbefore 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.
-
:.2fdisplays 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.
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.