Python Fundamentals · Python Basics

f-strings: Putting Values into Text

Put variables and expressions straight into text, and control decimals and alignment with format specs.

fstrings.py

item = "tea"
price = 2.5
qty = 3
cost = price * qty
receipt = f"{qty} x {item} = {cost}"
money = f"Total: {cost:.2f}"         # .2f: always two decimal places
padded = f"[{item:>6}]"              # >6: right-align in 6 characters
math = f"{qty + 1} cups next time"   # any expression works inside { }
print(receipt)
print(money, padded, math)

Step by step

  1. item is created with the value 'tea'.
  2. price is created with the value 2.5.
  3. qty is created with the value 3.
  4. The cost: 2.5 × 3 = 7.5.
  5. An f-string: the f before the quote means every {name} is replaced by its value.
  6. :.2f formats the number with exactly two decimals: 7.50.
  7. :>6 right-aligns "tea" in 6 characters, padding with spaces on the left.
  8. Any expression works inside the braces: qty + 1 = 4.
  9. It prints 3 x tea = 7.5.
  10. f-strings put values into text cleanly; the part after the colon controls how each value looks.