Python f-Strings
Table of Contents
In the last lesson, we learned how to get user input. Now let’s learn how f-strings make output cleaner.
After learning Python Getting User Input, our programs can collect values from a user. Now let’s display those values in clean, readable sentences. In this tutorial, we’ll learn about Python f-strings with easy examples.
🖨️ Let’s Talk About Printing Nicely
We know how to print things. We know how to use variables. But sometimes, printing gets messy. Let me show what I mean.
name = "Alex"age = 25city = "London"Now we want to print: “Alex is 25 years old and lives in London.” How do we do it?
We could do this:
print(name + " is " + str(age) + " years old and lives in " + city)It works. But look at it. It is ugly. Hard to read. And we have to convert age to a string.
Or we could do this:
print(name, "is", age, "years old and lives in", city)This is easier. But it adds spaces automatically. And sometimes we don’t want that.
There is a better way. It is called f-strings.
✨ What Is an f-String in Python?
An f-string is a special type of string. It lets us put variables directly inside it. Without any extra work. The “f” stands for “formatted.” Because it formats the string for us. Let me show.
name = "Alex"age = 25city = "London"
print(f"{name} is {age} years old and lives in {city}")Output
Alex is 25 years old and lives in LondonLook at that. Clean. Simple. No str(). No + signs. No commas. That is the power of f-strings.
✍️ How to Create an f-String in Python
It is easy. Just put an f before the quotes.
f"This is an f-string"Then, inside the string, we put variables inside curly braces { }.
name = "Alex"print(f"Hello, {name}")Output
Hello, AlexThe {name} gets replaced with the value of name. That’s it. That’s how it works.
🧮 We Can Put Any Expression Inside f-Strings
It is not just variables. We can put any Python expression inside the curly braces.
age = 25print(f"Next year I will be {age + 1}")Output
Next year I will be 26See? It did the math for us.
print(f"2 plus 3 is {2 + 3}")Output
2 plus 3 is 5name = "alex"print(f"Your name in uppercase is {name.upper()}")Output
Your name in uppercase is ALEXWe can call functions. Do math. Anything.
💬 Python f-Strings: A Real-Life Example
Let’s say we are making a receipt program.
item = "Coffee"price = 4.50quantity = 3total = price * quantity
print(f"Item: {item}")print(f"Price: ${price}")print(f"Quantity: {quantity}")print(f"Total: ${total}")Output
Item: CoffeePrice: $4.5Quantity: 3Total: $13.5Clean. Readable. Easy. Now compare that to the old way:
print("Item: " + item)print("Price: $" + str(price))print("Quantity: " + str(quantity))print("Total: $" + str(total))See the difference? The f-string version is much cleaner.
🔢 Formatting Numbers with Python f-Strings
Here is where f-strings get really useful. Sometimes we want to control how a number looks. Like showing only 2 decimal places.
price = 4.5print(f"Price: ${price:.2f}")Output
Price: $4.50See that :.2f? That means: format as a float with 2 decimal places.
Let me break it down:
:means “here comes the format”.2means “2 decimal places”fmeans “float”
So {price:.2f} gives us 4.50.
If we had 3.14159:
pi = 3.14159print(f"Pi is approximately {pi:.2f}")Output
Pi is approximately 3.14And with 3 decimals:
print(f"Pi is approximately {pi:.3f}")Output
Pi is approximately 3.142This is very useful for money and measurements.
🧾 Adding Commas to Big Numbers in Python f-Strings
If we have a big number, we can add commas to make it readable.
population = 8000000000print(f"World population: {population:,}")Output
World population: 8,000,000,000That comma makes a big difference. It is much easier to read.
↔️ Padding and Aligning in Python f-Strings
We can also control the width of the output.
name = "Alex"print(f"{name:>10}")Output
AlexThe >10 means: right-align in a space of 10 characters.
print(f"{name:<10}")Output
AlexThe <10 means: left-align in a space of 10 characters.
print(f"{name:^10}")Output
AlexThe ^10 means: center in a space of 10 characters. This is useful when we want to make tables that line up.
📊 Python f-Strings: A Real-Life Table Example
Let’s make a simple table.
print(f"{'Name':<10} {'Age':>5}")print("-" * 16)print(f"{'Alex':<10} {25:>5}")print(f"{'Sam':<10} {30:>5}")print(f"{'John':<10} {22:>5}")Output
Name Age----------------Alex 25Sam 30John 22See how the columns line up? That is the power of formatting.
⚙️ Expressions Inside Python f-Strings
We can put any valid Python expression inside the curly braces.
x = 10y = 3
print(f"{x} + {y} = {x + y}")print(f"{x} - {y} = {x - y}")print(f"{x} * {y} = {x * y}")print(f"{x} / {y} = {x / y}")Output
10 + 3 = 1310 - 3 = 710 * 3 = 3010 / 3 = 3.3333333333333335We can also use functions and methods.
name = "alex"print(f"Hello, {name.capitalize()}!")Output
Hello, Alex!🪆 Nested Quotes in Python f-Strings
Here is a nice thing about f-strings. We can use different quotes inside and outside.
name = "Alex"print(f'Hello, {name}')Single quotes outside. Works fine.
name = "Alex"print(f"Hello, {name}")Double quotes outside. Also works. If we need quotes inside the f-string, we use the other type.
name = "Alex"print(f"He said \"Hello, {name}\"")Output
He said "Hello, Alex"Or we use single quotes inside:
print(f'He said "Hello, {name}"')Output
He said "Hello, Alex"See? No escape needed.
⚡ Python f-Strings Are Fast
Here is a bonus fact. f-strings are faster than the old ways of formatting strings. There are other ways to format strings in Python:
%formatting — old style.format()— newer style- f-strings — newest and fastest
f-strings are not just easier to read. They are also faster. So let’s use them. Always.
🧪 A Complete Python f-String Example
Let’s put everything together.
# Get user infoname = input("Enter your name: ")age = int(input("Enter your age: "))salary = float(input("Enter your monthly salary: "))
# Calculate yearly salaryyearly = salary * 12
# Print a nice summaryprint()print(f"Hello, {name}!")print(f"You are {age} years old.")print(f"Your monthly salary is ${salary:,.2f}")print(f"Your yearly salary is ${yearly:,.2f}")Example output:
Enter your name: AlexEnter your age: 25Enter your monthly salary: 5000
Hello, Alex!You are 25 years old.Your monthly salary is $5,000.00Your yearly salary is $60,000.00See how nice that looks? The numbers have commas. The decimals are controlled. The text is clean. That is f-strings in action.
⚠️ Common Mistakes with Python f-Strings
🧭 Mistake 1: Forgetting the f
name = "Alex"print("{name}") # This prints {name}, not AlexOutput
{name}Why? Because there is no f at the start. Python thinks it is a normal string.
So what do we do? We add the f.
print(f"{name}")🖥 Mistake 2: Using the Wrong Brackets
name = "Alex"print(f"(name)") # This prints (name)So what do we do? We use curly braces.
print(f"{name}")🐍 Mistake 3: Forgetting to Close the Brace
print(f"Hello, {name")This gives an error. Because the curly brace is not closed.
So what do we do? We close the brace.
print(f"Hello, {name}")☕ Mistake 4: Using f-String in Python 2
f-strings were introduced in Python 3.6. If we are using an older version, they will not work. But we should be using Python 3.6 or newer anyway. So this should not be a problem.
Next, we will learn about Python Data Types Overview so we can continue step by step.