Velamuvi AIAcademy

Lesson 9 of 16 · Working With Text and Data

String Formatting With f-Strings

Master Python f-strings: decimal places, thousands separators, percentages, padding and alignment, debugging with = and formatting dates, with runnable examples.

  • 8 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How to control decimal places, separators and percentages
  • How to pad and align text into neat columns
  • How to debug quickly with the = sign
  • How to include quotes and curly brackets safely

A quick reminder

An f-string has an f before the opening quote. Anything inside curly brackets is worked out and inserted into the text.

Try it yourselfPython
name = "Ada"
lessons = 30

print(f"{name} finished {lessons} lessons.")
print(f"That is {lessons * 20} minutes of study.")
print(f"Her name has {len(name)} letters and starts with {name[0]}.")

Inside the brackets you can put any expression: a variable, a calculation, a function call or a method call.

Format specifications

After the expression you can add a colon and a format specification: a short code that says how the value should look.

Try it yourselfPython
price = 1234.5

print(f"{price}")
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{price:.0f}")
CodeMeaning1234.5 becomes
.2fexactly 2 decimal places1234.50
,.2fcomma every three digits, 2 decimals1,234.50
.0fno decimals, rounded1234

The rounding only changes how the number is shown. The variable keeps its exact value.

Big numbers and percentages

Try it yourselfPython
users = 15000000
accuracy = 0.9374

print(f"{users:,} users")
print(f"{users:_} users")
print(f"Accuracy: {accuracy:.1%}")
print(f"Accuracy: {accuracy:.0%}")

The % code multiplies by 100 and adds a percent sign, so you never have to do it yourself. The , separator groups digits in threes, the international style.

Padding and alignment

A number after the colon sets a minimum width. The value is padded with spaces to fill it. Arrows choose the alignment.

Try it yourselfPython
print(f"[{'left':<10}]")
print(f"[{'right':>10}]")
print(f"[{'centre':^10}]")
print(f"[{'stars':*^11}]")
print(f"[{7:03}]")
  • < aligns left, > aligns right, ^ centres.
  • A character before the arrow, like *, is used instead of spaces.
  • 03 pads a number with zeros to three digits.

Building a neat table

Widths make columns line up, which is perfect for small reports in the terminal.

Try it yourselfPython
results = [("Linear model", 0.81), ("Random forest", 0.874), ("Neural net", 0.9123)]

print(f"{'Model':<15}{'Accuracy':>10}")
print("-" * 25)
for model, score in results:
    print(f"{model:<15}{score:>10.1%}")

Text columns usually align left and number columns align right, so the decimal points line up.

Debugging with the = sign

Add = after an expression and the f-string prints the expression and its value. It is the quickest way to check what your variables hold.

Try it yourselfPython
learning_rate = 0.001
epochs = 20
batch = [3, 1, 4]

print(f"{learning_rate=}")
print(f"{epochs * 2=}")
print(f"{len(batch)=}")

Quotes and curly brackets

If the f-string uses double quotes, use single quotes inside the brackets, and the other way round.

Try it yourselfPython
student = {"name": "Grace", "score": 85}

print(f"{student['name']} scored {student['score']}")

To show a real curly bracket, write it twice.

Try it yourselfPython
key = "temperature"

print(f"Use the setting {{{key}}} in your template")
print(f"{{ and }} are written twice")

Long f-strings

Python joins strings that sit next to each other inside brackets. That lets you split a long f-string over several lines.

Try it yourselfPython
name, course, score = "Mei", "SQL for Beginners", 0.96

message = (
    f"Congratulations {name}! "
    f"You finished {course} "
    f"with a score of {score:.0%}."
)
print(message)

Common mistakes

Practice exercise

Use widths, alignment and decimal places to print a tidy receipt.

Your solutionPython
items = [("Notebook", 2, 45.5), ("Pen", 10, 12), ("Backpack", 1, 899)]

# Print one line per item: the name left-aligned in 10 characters,
# then the quantity right-aligned in 4,
# then the line total (quantity * price) right-aligned in 10 with 2 decimals.
# Output must be exactly:
# Notebook     2     91.00
# Pen         10    120.00
# Backpack     1    899.00
Knowledge check

What does f'{0.256:.1%}' produce?

Summary

  • Put an expression in curly brackets, and add :spec to control how it looks.
  • .2f sets decimals, , adds separators, and .1% shows a percentage.
  • <, > and ^ with a width align text into columns.
  • {value=} prints the expression and its value, which is great for debugging.
  • Write {{ and }} for literal curly brackets.

Next: JSON, the format that almost every API speaks.

Finished reading? Tick it off to track your progress.