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
— step through the idea, then dive into the details below.Stop Gluing Strings Together
Concatenating text with + gets messy fast. f-strings let you drop values right inside a string — clean, readable, no fuss.
#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.
name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)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.
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
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 :,
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.
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}")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.
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.
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))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.
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} ``
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.
What does this code print?
name = "Sam"
score = 9.5
print(f"{name} scored {score:.0f} out of 10.")This code has a bug. What is wrong?
city = "Paris"
population = 2161000
print("Population of {city}: {population:,}")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:}")
Put these lines in the right order to print a tidy two-column table showing an item and its price.
item = "Notebook"
price = 3.99
print(f"{item:<12} {price:>8.2f}")print(f"{'Item':<12} {'Price':>8}")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: