Skip to main content
Editor

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

Beginner20 min5 exercises75 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

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
name = "Alice"
age = 30
city = "Seattle"
print(f"My name is {name}.")
print(f"I am {age} years old.")
print(f"I live in {city}.")
Output
My name is Alice.
I am 30 years old.
I live in Seattle.

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
# Without the f prefix - curly braces are printed literally
name = "Alice"
print("Hello, {name}!") # No f prefix
print(f"Hello, {name}!") # With f prefix
Output
Hello, {name}!
Hello, Alice!

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
# Math expressions
width = 10
height = 5
print(f"Area: {width * height} square units")
# Function and method calls
name = "python"
print(f"Length: {len(name)}")
print(f"Uppercase: {name.upper()}")
# Conditional expressions
score = 85
print(f"Result: {'Pass' if score >= 60 else 'Fail'}")
Output
Area: 50 square units
Length: 6
Uppercase: PYTHON
Result: Pass

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
price = 4.5
pi = 3.14159265
print(f"Price: ${price:.2f}") # 2 decimal places
print(f"Pi: {pi:.4f}") # 4 decimal places
print(f"Rounded: {pi:.1f}") # 1 decimal place
Output
Price: $4.50
Pi: 3.1416
Rounded: 3.1

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
population = 8900000
salary = 75000.50
print(f"Population: {population:,}")
print(f"Salary: ${salary:,.2f}")
Output
Population: 8,900,000
Salary: $75,000.50

Percentages with %

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

Formatting percentages
completion = 0.756
tax_rate = 0.0825
print(f"Progress: {completion:.1%}") # 75.6%
print(f"Tax rate: {tax_rate:.2%}") # 8.25%
Output
Progress: 75.6%
Tax rate: 8.25%

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
# Width and alignment
print(f"|{'Left':<15}|") # Left-aligned, 15 chars wide
print(f"|{'Center':^15}|") # Center-aligned
print(f"|{'Right':>15}|") # Right-aligned
# Numbers default to right-aligned
print(f"|{42:>10}|") # Right-aligned number
print(f"|{42:010}|") # Zero-padded to 10 digits
Output
|Left           |
|    Center     |
|          Right|
|        42|
|0000000042|

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()
name = "Bob"
age = 25
# Positional arguments
print("Hello, {}! You are {} years old.".format(name, age))
# Numbered positions
print("Hello, {0}! You are {1} years old. Nice to meet you, {0}!".format(name, age))
# Named arguments
print("Hello, {n}! You are {a} years old.".format(n=name, a=age))
Output
Hello, Bob! You are 25 years old.
Hello, Bob! You are 25 years old. Nice to meet you, Bob!
Hello, Bob! You are 25 years old.

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

Number formatting with .format()
price = 19.99
print("Price: ${:.2f}".format(price))
print("Big number: {:,}".format(1000000))
Output
Price: $19.99
Big number: 1,000,000

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
name = "Charlie"
age = 35
price = 9.99
print("Hello, %s! You are %d years old." % (name, age))
print("Price: $%.2f" % price)
Output
Hello, Charlie! You are 35 years old.
Price: $9.99

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
item = "Coffee"
price = 4.50
# f-string (Python 3.6+) - recommended
print(f"{item}: ${price:.2f}")
# .format() method (Python 2.6+)
print("{}: ${:.2f}".format(item, price))
# % operator (oldest style)
print("%s: $%.2f" % (item, price))
Output
Coffee: $4.50
Coffee: $4.50
Coffee: $4.50

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
name = "Alice"
order_id = 4821
total = 37.50
message = f"""Hi {name},
Your order #{order_id} has been confirmed.
Total: ${total:.2f}
Thank you for shopping with us!"""
print(message)
Output
Hi Alice,

Your order #4821 has been confirmed.
Total: $37.50

Thank you for shopping with us!

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

Building a formatted table
# Simple formatted table
products = [
("Laptop", 999.99, 1),
("Mouse", 29.50, 3),
("Keyboard", 74.00, 2),
]
print(f"{'Product':<12} {'Price':>8} {'Qty':>5} {'Total':>10}")
print("-" * 37)
for name, price, qty in products:
total = price * qty
print(f"{name:<12} {price:>8.2f} {qty:>5} {total:>10.2f}")
Output
Product         Price   Qty      Total
-------------------------------------
Laptop         999.99     1     999.99
Mouse           29.50     3      88.50
Keyboard        74.00     2     148.00
The = debug shortcut
# Debug trick (Python 3.8+)
x = 42
y = 17
print(f"{x=}")
print(f"{y=}")
print(f"{x + y=}")
Output
x=42
y=17
x + y=59

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 price should show exactly 2 decimal places. Use the string " .......... $" between the name and price.

# Create the variables and print the formatted receipt line
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
# Format the population with commas
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+  |
    # Create the variables and print the formatted table row
    Fix the Broken f-string
    Fix the Bug

    The code below is supposed to print "Hello, Sam! You scored 92.5%." but it prints the curly braces instead of the values. Find and fix the bug.

    name = "Sam"
    score = 0.925
    print("Hello, {name}! You scored {score:.1%}.")
    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.

    # Create the variables and print the email greeting

    Harder problems

    More problems on this topic: Strings

    Related Tutorials

    Was this tutorial helpful?