f-strings and .format()
What You'll Learn
- What f-strings are and why they are the preferred way to format strings
- How to embed expressions inside f-strings
- Formatting numbers (decimal places, commas, percentages)
- Text alignment and padding
- The older
.format()method
1. Introduction to f-strings
f or F that allows you to embed Python expressions inside curly braces {}. Introduced in Python 3.6, f-strings are the modern, preferred way to format strings.
name = "Alice" age = 25 # Without f-strings (old way) print("My name is " + name + " and I am " + str(age) + " years old.") # With f-strings (much cleaner!) print(f"My name is {name} and I am {age} years old.")
Notice how much cleaner the f-string version is. No + signs, no str() calls -- just put the variable name inside {} and Python handles the rest!
f before the opening quote. Without the f, the curly braces are treated as literal characters.
2. Expressions Inside f-strings
You can put any valid Python expression inside the curly braces, not just variable names:
x = 10 y = 3 # Math expressions print(f"{x} + {y} = {x + y}") print(f"{x} * {y} = {x * y}") # Function calls name = "alice" print(f"Name: {name.upper()}") print(f"Length: {len(name)}")
Practical: Temperature Converter
fahrenheit = 98.6 celsius = (fahrenheit - 32) * 5 / 9 print(f"{fahrenheit}F = {round(celsius, 1)}C")
3. Formatting Numbers
f-strings have a powerful mini-language for formatting numbers. Add a colon : after the expression, followed by formatting instructions:
Decimal Places
pi = 3.14159265 price = 9.5 print(f"Pi: {pi:.2f}") # 2 decimal places print(f"Pi: {pi:.4f}") # 4 decimal places print(f"Price: ${price:.2f}") # Always show 2 decimals
Comma Separators for Large Numbers
population = 8000000 salary = 75000.50 print(f"Population: {population:,}") print(f"Salary: ${salary:,.2f}")
Percentages
score = 0.875 print(f"Score: {score:.1%}") # Multiply by 100, add % ratio = 17 / 23 print(f"Ratio: {ratio:.2%}")
| Format | Meaning | Example | Result |
|---|---|---|---|
:.2f | 2 decimal places | f"{3.14159:.2f}" | 3.14 |
:, | Comma separator | f"{1000000:,}" | 1,000,000 |
:,.2f | Commas + decimals | f"{1234.5:,.2f}" | 1,234.50 |
:.1% | Percentage | f"{0.85:.1%}" | 85.0% |
4. Text Alignment and Padding
You can control text alignment within a specified width:
item = "Apples" price = 1.50 # Left align (default for strings) print(f"|{item:<15}|") # Right align print(f"|{item:>15}|") # Center align print(f"|{item:^15}|")
Practical: A Formatted Receipt
print(f"{'Item':<15} {'Price':>8}") print("-" * 24) print(f"{'Apples':<15} {'$1.50':>8}") print(f"{'Bread':<15} {'$3.99':>8}") print(f"{'Milk':<15} {'$4.25':>8}") print("-" * 24) print(f"{'Total':<15} {'$9.74':>8}")
5. The .format() Method
Before f-strings existed, Python used the .format() method. You may encounter it in older code:
name = "Alice" age = 25 # Using .format() print("My name is {} and I am {} years old.".format(name, age)) # With numbered positions print("My name is {0} and I am {1} years old.".format(name, age)) # With named placeholders print("My name is {n} and I am {a} years old.".format(n=name, a=age))
The same formatting options work with .format():
print("Pi is approximately {:.2f}".format(3.14159)) print("Population: {:,}".format(8000000))
.format() so you can read older Python code.
6. Combining f-strings with input()
name = input("Enter your name: ") hours = float(input("Hours worked: ")) rate = float(input("Hourly rate: $")) pay = hours * rate print(f"\n--- Pay Summary for {name} ---") print(f"Hours: {hours}") print(f"Rate: ${rate:.2f}/hr") print(f"Pay: ${pay:,.2f}")
Check Your Understanding
Question 1: What does f"{3.14159:.3f}" produce?
Answer: 3.142 -- rounds to 3 decimal places.
Question 2: How do you display 0.75 as a percentage with 1 decimal place?
Answer: f"{0.75:.1%}" produces 75.0%
Try It Yourself!
- Use an f-string to print "My name is [name] and I am [age] years old" with your own values.
- Format the number 1234567.891 to show commas and 2 decimal places.
- Create a formatted table with 3 items and prices, right-aligned prices.
Key Takeaways
- f-strings start with
fand allow expressions inside{}. - You can put any valid Python expression inside the curly braces.
- Use
:.2ffor decimal places,:,for commas,:.1%for percentages. - Alignment:
<left,>right,^center (with a width number). .format()is the older method -- know it for reading older code, but prefer f-strings.