By the end of this lesson, you will be able to format strings in Python using both the format() method and f-strings, choosing the right tool for dynamic text generation.
What it is
String formatting is the process of inserting variables or expressions into a string template. In Python, there are two primary modern approaches: the str.format() method and f-strings (formatted string literals). The format() method uses curly braces {} as placeholders within a string, which are then replaced by values passed as arguments. F-strings, introduced in Python 3.6, allow you to embed expressions directly inside string literals prefixed with an f.
Related terms include "placeholders," "interpolation," and "string templates."
Why it matters
- Readability: Formatting keeps your code clean by separating the structure of the output from the data being inserted.
- Flexibility: You can control precision, alignment, and padding without complex concatenation logic.
- Maintainability: Changing the order of arguments or modifying the layout is easier than managing multiple string joins.
- Performance: F-strings are generally faster than
format()because they are evaluated at runtime rather than parsed as a separate method call.
Syntax or steps
The basic syntax for format() involves calling the method on a string containing placeholders:
"template {}".format(value)
You can use positional indices like {0} or named keys like {name}. For f-strings, simply prefix the string with f and place expressions inside curly braces:
f"template {expression}"
Example
Here is a comparison of both methods using a realistic scenario involving calculation results:
# Using str.format()
result = "{} + {} = {}".format(1, 2, 3)
print(result)
# Using f-strings (Recommended for most cases)
a = 1
b = 2
c = a + b
f_result = f"{a} + {b} = {c}"
print(f_result)
# Advanced formatting with precision
pi = 3.14159
formatted_pi = f"The value of pi is approximately {pi:.2f}"
print(formatted_pi)
Explanation:
1. The first block uses format() where three placeholders {} are filled sequentially by the arguments 1, 2, and 3.
2. The second block uses an f-string. Variables a, b, and c are evaluated directly within the braces. This is often clearer because the variable names appear exactly where they are used.
3. The third block demonstrates formatting a float. The : .2f specifier tells Python to format the number as a fixed-point decimal with two digits after the point.
Common mistakes
- Forgetting the
fprefix: Writing"{var}"instead off"{var}"will print the literal text "{var}" rather than the variable's value. - Mismatched argument counts: With
format(), if you have more placeholders than arguments (or vice versa), Python raises anIndexErroror leaves placeholders unfilled. - Using quotes incorrectly in f-strings: Before Python 3.12, you could not use the same type of quote inside the expression as outside the string. For example,
f"{'hello'}"works, butf"{"hello"}"causes a syntax error in older versions. - Overcomplicating simple concatenation: Do not use
format()for static strings that don't change; simple concatenation or direct assignment is sufficient.
When to use it
| Feature | f-strings | str.format() |
|---|---|---|
| Best for | Most everyday coding, debugging, and quick scripts. | Templates stored separately from data, or when supporting Python < 3.6. |
| Readability | High (variables visible in context). | Medium (separation of template and data). |
| Performance | Faster. | Slower due to method call overhead. |
| Complexity | Can handle complex expressions inline. | Better for reusable template strings. |
Practice
Guided Exercise: Create a program that asks the user for their name and age, then prints a sentence saying "Hello [Name], you are [Age] years old." Use an f-string.
Challenge: Format a list of prices [10.5, 20.123, 5] so that each price is displayed with exactly two decimal places, aligned to the right in a column width of 8 characters. Hint: Use the format specifier :>8.2f.
Quick check
Question: What is the output of print(f"{10 / 3:.3f}")?
Answer: 3.333
Summary
Python offers robust string formatting through format() and f-strings. While format() provides flexibility for reusable templates, f-strings are preferred for their readability and performance in most modern applications. Mastering these tools allows you to generate clean, professional output efficiently.