🎓 A1Learner
🔍
0 of 116 lessons completed

Python Format Strings (f-strings)

An f-string is a string that places values right inside the text. The letter f before the opening quote marks an f-string.

Joining with plus signs

The number needs str() before it can join.

name = "Ada"
age = 36
print("Name: " + name + ", Age: " + str(age))

A first f-string

The letter f sits before the opening quote. Braces hold a placeholder for each value.

name = "Ada"
age = 36
print(f"Name: {name}, Age: {age}")

Expressions inside braces

Braces can hold a small sum, not just a name. Python works it out first, then shows the result.

price = 10
print(f"Double price: {price * 2}")

Two decimal places

The part after the colon is a format spec. A format spec tells Python how to show the value.

price = 9.5
print(f"Price: ${price:.2f}")

Thousands with commas

A comma in the format spec groups big numbers into thousands.

salary = 75000
print(f"Salary: ${salary:,}")

Example

item = "Notebook"
price = 12.50
tax_rate = 0.08
total = price + price * tax_rate
print(f"Item: {item}")
print(f"Price: ${price:.2f}")
print(f"Total with tax: ${total:.2f}")

Key points

  • Placeholder: a spot inside braces { } where a value goes
  • Use f before the opening quote to make a string an f-string
  • An f-string writes each value inside the text, at its placeholder.
  • Use an expression inside braces to show a worked-out value, like {price * 2}
  • Use :.2f inside braces to show a number with two decimal places
  • Use :, inside braces to add commas between thousands
  • F-strings are the clearest to read.

In this example, item holds the name Notebook. price holds 12.50 and tax_rate holds 0.08. total adds the price to the tax on that price. The first print shows the item name. The last two prints use :.2f, so each money value shows two decimal places.

Note

Older code uses "...".format(...) and the even older % style.

Both styles still work.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does this code print? print(f"{3.14159:.2f}")