🎓 A1Learner
🔍
0 of 116 lessons completed

Python Number Formatting

Number formatting controls how a number appears as text. A format spec gives the instructions after the colon inside braces.

Set the decimals

The number after the dot says how many decimal places to show.

value = 3.14159
print(f"{value:.2f}")

Reserve some width

A width pads the value with spaces. The value sits on the right by default.

number = 42
print(f"[{number:5}]")

Choose the alignment

One letter in the spec picks where the value sits in its space.

print(f"{42:<5}|")
print(f"{42:>5}|")
print(f"{42:^5}|")

Show a percent

A percent sign in the spec multiplies the value by 100. Python adds the % sign for you.

share = 0.856
print(f"Score: {share:.1%}")

Rounding ties

A tie is a value exactly halfway between two choices. Python sends ties to the even number.

print(f"{2.5:.0f}")
print(f"{3.5:.0f}")

Example

print(f"{'Name':<7}{'Score':>5}")
print(f"{'Ada':<7}{92:>5}")
print(f"{'Bob':<7}{85:>5}")
print(f"{'Cy':<7}{78:>5}")

Key points

  • Format spec: the instructions after the colon inside braces
  • Use .2f to show two decimal places and .0f to show none
  • Use a width like :5 to reserve five spaces for the value
  • Use < to align left, > to align right, and ^ to centre
  • Use % in the spec to show a value like 0.85 as a percent
  • Formatting changes how a number looks as text.
  • A tie at 3.5 rounds to 4.

In this example, the first print makes the table heading. Each name uses <7, so names start at the left in seven spaces. Each score uses >5, so scores end at the right in five spaces. The three rows follow the same pattern. That is why the scores line up in one neat column.

Note

Python rounds ties to the even number.

A tie at 2.5 rounds to 2.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does this code print? print(f"{0.5:.0%}")