1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

Format specifiers

Add a : inside the braces to control how a value looks:

f"{3.14159:.2f}"    # 3.14       2 decimal places
f"{1234567:,}"      # 1,234,567  thousands separator
f"{0.256:.1%}"      # 25.6%      percentage
f"{'hi':>6}"        # '    hi'   right-align in width 6

They combine: :,.2f means commas and 2 decimals.

See it run

pi = 3.14159
print(f"{pi:.2f}")
print(f"{pi:8.2f}|")
print(f"{pi}")

The bit after the colon inside {} is a format spec. It changes how a value is shown, never the value itself.

Practice format specifiers

Exercise 1

Print exactly two lines using format specifiers:

  • Price: $1,234.50 from price = 1234.5
  • Score: 87.5% from ratio = 0.875

Exercise 2

A weather widget shows one tidy line. Using city, temp and humidity, print exactly:

Oslo: -3.5°C, humidity 82%

  • the temperature with 1 decimal place
  • the humidity as a percentage with no decimals (.0%)

Exercise 3

Use the two items and prices in the code editor below to print a neat three-line receipt. Work out total = price1 + price2 first. On each line:

  • the label is left-aligned in width 10 (:<10)
  • the amount is right-aligned in width 7 with 2 decimals (:>7.2f)

The output should look like this:

Tea          3.50
Croissant    4.25
Total        7.75

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest