Learn Without Walls
← Previous Lesson Lesson 3 of 4 Next Lesson →

f-strings and .format()

What You'll Learn

1. Introduction to f-strings

f-string (formatted string literal): A string prefixed with 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.")
My name is Alice and I am 25 years old. My name is Alice and I am 25 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!

Remember: The string must start with 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)}")
10 + 3 = 13 10 * 3 = 30 Name: ALICE Length: 5

Practical: Temperature Converter

fahrenheit = 98.6
celsius = (fahrenheit - 32) * 5 / 9

print(f"{fahrenheit}F = {round(celsius, 1)}C")
98.6F = 37.0C

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
Pi: 3.14 Pi: 3.1416 Price: $9.50

Comma Separators for Large Numbers

population = 8000000
salary = 75000.50

print(f"Population: {population:,}")
print(f"Salary: ${salary:,.2f}")
Population: 8,000,000 Salary: $75,000.50

Percentages

score = 0.875
print(f"Score: {score:.1%}")    # Multiply by 100, add %

ratio = 17 / 23
print(f"Ratio: {ratio:.2%}")
Score: 87.5% Ratio: 73.91%
FormatMeaningExampleResult
:.2f2 decimal placesf"{3.14159:.2f}"3.14
:,Comma separatorf"{1000000:,}"1,000,000
:,.2fCommas + decimalsf"{1234.5:,.2f}"1,234.50
:.1%Percentagef"{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}|")
|Apples | | Apples| | Apples |

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}")
Item Price ------------------------ Apples $1.50 Bread $3.99 Milk $4.25 ------------------------ Total $9.74

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))
My name is Alice and I am 25 years old. My name is Alice and I am 25 years old. My name is Alice and I am 25 years old.

The same formatting options work with .format():

print("Pi is approximately {:.2f}".format(3.14159))
print("Population: {:,}".format(8000000))
Pi is approximately 3.14 Population: 8,000,000
Recommendation: Use f-strings for new code. They are more readable and faster. But know .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!

  1. Use an f-string to print "My name is [name] and I am [age] years old" with your own values.
  2. Format the number 1234567.891 to show commas and 2 decimal places.
  3. Create a formatted table with 3 items and prices, right-aligned prices.

Key Takeaways

← Previous: User Input Next: Concatenation →