Working with StringsBeginner8 min20 / 63

String Formatting & f-strings

Learn how to build beautiful, dynamic strings in Python using f-strings — the modern, readable way to mix variables and text.

Imagine you want to greet a user by name, show a price with exactly two decimal places, or print a tidy table of numbers. You could glue strings together with +, but that gets messy fast. String formatting is Python's clean solution: a way to embed values directly inside a string, right where you need them.

See it in action

Visual walkthrough1 / 5
1

Stop Gluing Strings Together

Concatenating text with + gets messy fast. f-strings let you drop values right inside a string — clean, readable, no fuss.

f-strings are the modern Python way — use them in all new code.

#Meet f-strings

An f-string is a string with a lowercase f in front of the opening quote. Inside the string, anything you put between {curly braces} gets evaluated and inserted automatically. That's it — no gluing, no conversion, no fuss.

The f before the quote activates f-string mode. Curly braces are replaced with the variable's value.
name = "Alice"
age = 30

greeting = f"Hello, {name}! You are {age} years old."
print(greeting)
Think of it like

Think of it like a mail merge

Remember those letters that say "Dear [YOUR NAME], you have won..."? An f-string works the same way — you write a template with placeholders, and Python fills them in automatically.

#Embedding Expressions

The curly braces in an f-string can hold any Python expression — not just variable names. You can do math, call functions, or combine values, all inside the string.

You can put math, method calls, or any expression right inside the braces.
items = 4
price_each = 2.5

print(f"You bought {items} items.")
print(f"Total: {items * price_each}")
print(f"2 + 2 = {2 + 2}")
print(f"Name uppercase: {'alice'.upper()}")

#Format Specs: Controlling How Values Look

After the variable name inside the braces, you can add a colon : followed by a format spec — a small code that tells Python exactly how to display the value. This is incredibly useful for numbers, alignment, and readability.

#Decimal Places with :.2f

:.2f means: format as a fixed-point float with exactly 2 decimal places.
price = 9.5
tax = 0.08
total = price * (1 + tax)

print(f"Price:  ${price:.2f}")
print(f"Total:  ${total:.2f}")

The spec :.2f breaks down like this: - .2 — show 2 digits after the decimal point - f — treat the number as a float (fixed-point)

You can change 2 to any number: :.0f gives no decimals, :.4f gives four.

#Thousands Separator with :,

The comma in the format spec adds thousand-separators, making large numbers much easier to read.
population = 8100000000
revenue = 1234567.89

print(f"World population: {population:,}")
print(f"Revenue: ${revenue:,.2f}")

#Alignment and Padding

When printing tables or columns, you often want values to line up neatly. Format specs let you set a minimum width and choose left (<), right (>), or center (^) alignment.

:<12 means left-align in a field 12 chars wide. :>8.2f means right-align in 8 chars with 2 decimal places.
print(f"{'Item':<12} {'Price':>8}")
print(f"{'Coffee':<12} {3.50:>8.2f}")
print(f"{'Sandwich':<12} {7.99:>8.2f}")
print(f"{'Orange Juice':<12} {4.25:>8.2f}")
Tip

Format spec cheat sheet

| Spec | Meaning | Example | |------|---------|--------| | :.2f | 2 decimal places | 3.50 | | :, | thousands separator | 1,000,000 | | :>10 | right-align, width 10 | hello | | :<10 | left-align, width 10 | hello | | :^10 | center, width 10 | hello | | :,.2f | both comma and decimals | 1,234.56 |

#Multiline f-strings

You can use triple quotes (""") with f-strings to write strings that span multiple lines. This is great for building longer messages or simple reports.

Triple-quoted f-strings keep your newlines and indentation intact.
name = "Bob"
balance = 1025.5
transactions = 3

report = f"""
Account Summary
---------------
Holder:       {name}
Balance:      ${balance:,.2f}
Transactions: {transactions}
"""
print(report)

#Older Formatting Styles (for recognition)

You will sometimes see older Python code using two other formatting styles. You don't need to write them, but knowing what they look like helps you read existing code.

Both do the same job as f-strings. Prefer f-strings in new code — they are cleaner and easier to read.
name = "Carol"
age = 25

# .format() style — older but still common
print("Hello, {}! You are {} years old.".format(name, age))

# % style — the oldest way, rarely used now
print("Hello, %s! You are %d years old." % (name, age))
Common mistake

Don't forget the f!

A very common mistake is writing a string with curly braces but forgetting the `f` prefix. Python will not substitute anything — it will print the literal braces and variable name.

``python name = "Dave" print("Hello, {name}") # Wrong! Prints: Hello, {name} print(f"Hello, {name}") # Right! Prints: Hello, Dave ``

If your curly-brace substitution is not working, check for the missing f first.

Watch out

Curly braces inside f-strings

If you actually need to print a literal { or } character inside an f-string, double them up: {{ prints { and }} prints }.

``python print(f"Set notation: {{1, 2, 3}}") # Output: Set notation: {1, 2, 3} ``

Quick check

What will the following code print? ```python value = 1234567.891 print(f"{value:,.1f}") ```

Key takeaways

  • Put `f` before a string to make it an f-string — then use `{variable}` to embed any value or expression.
  • Add a format spec after a colon inside the braces: `:.2f` for 2 decimal places, `:,` for thousands separators, `:<10` or `:>10` for alignment.
  • You can put any Python expression inside the braces — math, function calls, method calls.
  • Triple-quoted f-strings (`f"""..."""`) span multiple lines and are great for reports or messages.
  • You may see `.format()` and `%` formatting in older code — they work, but f-strings are the modern, preferred choice.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this code print?

predict-output
name = "Sam"
score = 9.5
print(f"{name} scored {score:.0f} out of 10.")
Fix the bug#2

This code has a bug. What is wrong?

fix-bug
city = "Paris"
population = 2161000
print("Population of {city}: {population:,}")
Fill in the blank#3

Complete the f-string so it prints the total formatted with a thousands separator and exactly 2 decimal places.

total = 9875.6
print(f"Grand total: ${total:}")
Reorder the lines#4

Put these lines in the right order to print a tidy two-column table showing an item and its price.

1
item = "Notebook"
2
price = 3.99
3
print(f"{item:<12} {price:>8.2f}")
4
print(f"{'Item':<12} {'Price':>8}")
Your turn
Practice exercise

Write a Python program that defines three variables: a product name (string), a unit price (float), and a quantity (integer). Then print a formatted receipt that shows the product name left-aligned in a 20-character field, the unit price formatted to 2 decimal places, the quantity, and the total cost (price × quantity) formatted with 2 decimal places and a dollar sign.

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable