Skip to main content

Python String Formatting: f-strings, format(), and % Operator

Beginner20 min5 exercises75 XP
0/5 exercises

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.

Concatenation (messy)
name = "Latte"
price = 4.5
qty = 2
print("Item: " + name + " | Price: $" + str(price) + " | Qty: " + str(qty))
f-string (clean)
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.

Basic f-string usage
Loading editor...

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 happens without the f prefix
Loading editor...

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.

Expressions inside f-strings
Loading editor...

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.

Controlling decimal places
Loading editor...

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.

Adding comma separators
Loading editor...

Percentages with %

Use :.N% to display a decimal as a percentage. Python multiplies the value by 100 and adds the % sign automatically.

Formatting percentages
Loading editor...

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.

Padding and alignment
Loading editor...

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.

Using .format()
Loading editor...

The .format() method supports the same format specifiers as f-strings. Everything after the colon works identically.

Number formatting with .format()
Loading editor...

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.

Old-style % formatting
Loading editor...

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:

Three ways to format the same string
Loading editor...

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.

Multiline f-string
Loading editor...

Here's a practical example: building a formatted table. Alignment specifiers make each column line up neatly.

Building a formatted table
Loading editor...
The = debug shortcut
Loading editor...

Practice Exercises

Format a Receipt Line
Write Code

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.50

The item name should be left-aligned and the price should show exactly 2 decimal places. Use the string " .......... $" between the name and price.

Loading editor...
Format a Large Number with Commas
Write Code

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,000
Loading editor...
Create a Formatted Table Row
Write Code

Create three variables: name = "Alice", score = 95.8, and grade = "A+". Print a formatted table row where:

  • The name is left-aligned in a 10-character-wide field
  • The score is right-aligned in an 8-character-wide field with 1 decimal place
  • The grade is center-aligned in a 6-character-wide field
  • Expected output (the | characters are part of the output):

    | Alice      |     95.8 |  A+   |
    Loading editor...
    Fix the Broken f-string
    Fix the Bug

    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.

    Loading editor...
    Generate a Personalized Email Greeting
    Write Code

    Create these variables:

  • first_name = "Jordan"
  • items = 3
  • total = 89.95
  • Then 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.

    Loading editor...