Python String Formatting: f-strings, format(), and % Operator
Imagine you're building a receipt for a coffee shop. You need to combine a product name, a price, and a quantity into one clean line. You could glue strings together with +, but it gets messy fast.
String formatting is like a fill-in-the-blank template. You write the sentence structure once, then drop in the values wherever they belong. It's cleaner, faster, and far easier to read.
Python gives you three ways to format strings: f-strings, the `.format()` method, and the `%` operator. In this tutorial, you'll learn all three and discover which one to use when.
Why String Formatting Is Better Than Concatenation
When beginners first combine variables with text, they reach for the + operator. It works, but it forces you to manually convert numbers to strings and sprinkle + signs everywhere.
name = "Latte"
price = 4.5
qty = 2
print("Item: " + name + " | Price: $" + str(price) + " | Qty: " + str(qty))name = "Latte"
price = 4.5
qty = 2
print(f"Item: {name} | Price: ${price} | Qty: {qty}")Both lines produce the same output. But the f-string version is shorter, easier to read, and you never have to call str() yourself. Python handles the conversion automatically.
How to Use f-strings in Python
An f-string (formatted string literal) starts with the letter f before the opening quote. Inside the string, you place variables or expressions inside curly braces {}.
Python evaluates whatever is inside the braces and inserts the result into the string. It was introduced in Python 3.6 and is now the recommended way to format strings.
The f before the quotes is what makes this special. Without it, Python would print the literal text {name} instead of the variable's value.
What Expressions Can You Put Inside f-strings?
f-strings aren't limited to simple variables. You can put any valid Python expression inside the curly braces — math, function calls, method calls, even conditionals.
Think of each {} as a tiny calculator. Python evaluates the expression, converts the result to a string, and drops it into place.
How to Format Numbers in Python f-strings
This is where f-strings really shine. After a variable name, you add a colon : followed by a format specifier that controls how the number looks.
Decimal Places with .Nf
Use :.Nf to show exactly N decimal places. The f stands for "fixed-point" notation. This is essential for displaying prices, measurements, and scores.
Comma Separators for Large Numbers
Use :, to add comma separators to large numbers. This makes numbers like 1000000 much easier to read at a glance.
Percentages with %
Use :.N% to display a decimal as a percentage. Python multiplies the value by 100 and adds the % sign automatically.
Padding and Alignment
You can set a minimum width for a value and control whether it aligns left, right, or center. This is perfect for building clean, aligned output like tables.
How to Use the .format() Method
Before f-strings existed, Python developers used the .format() method. It works by placing empty {} placeholders in a string, then calling .format() with the values to fill in.
The .format() method supports the same format specifiers as f-strings. Everything after the colon works identically.
Numbered positions are useful when you need to repeat a value multiple times in the same string. You reference the same index as many times as you want.
The % Operator for String Formatting (Old Style)
The % operator is the oldest way to format strings in Python. It's borrowed from C's printf function. You'll see it in older code and should recognize it, but you don't need to use it in new code.
The %s means "insert a string here," %d means "insert an integer," and %f means "insert a float." The values go after the % operator at the end.
f-strings vs format() vs % Operator: Which Should You Use?
All three approaches produce the same result. The difference is readability and convenience. Here's the same output written three ways:
Multiline f-strings and Real-World Patterns
For longer formatted strings, you can use triple quotes with the f prefix. This is handy for multi-line messages, reports, and email templates.
Here's a practical example: building a formatted table. Alignment specifiers make each column line up neatly.
Practice Exercises
Create variables item set to "Cappuccino" and price set to 4.5. Then use an f-string to print a receipt line in this exact format:
Cappuccino .......... $4.50The item name should be left-aligned and the price should show exactly 2 decimal places. Use the string " .......... $" between the name and price.
Create a variable population set to 7900000000. Print it using an f-string with comma separators so the output is:
World population: 7,900,000,000Create three variables: name = "Alice", score = 95.8, and grade = "A+". Print a formatted table row where:
Expected output (the | characters are part of the output):
| Alice | 95.8 | A+ |The code below is supposed to print "Hello, Sam! You scored 92.5%." but it has bugs. Find and fix them.
There are 2 bugs to fix.
Create these variables:
first_name = "Jordan"items = 3total = 89.95Then use a multiline f-string (triple quotes) to print this exact message:
Hi Jordan,
Thank you for your purchase of 3 items.
Your total is $89.95.
Have a great day!Make sure the total shows exactly 2 decimal places.