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
- 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.
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.
price = 1234.5
print(f"{price}")
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{price:.0f}")| Code | Meaning | 1234.5 becomes |
|---|---|---|
.2f | exactly 2 decimal places | 1234.50 |
,.2f | comma every three digits, 2 decimals | 1,234.50 |
.0f | no decimals, rounded | 1234 |
The rounding only changes how the number is shown. The variable keeps its exact value.
Big numbers and percentages
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.
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. 03pads 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.
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.
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.
student = {"name": "Grace", "score": 85}
print(f"{student['name']} scored {student['score']}")To show a real curly bracket, write it twice.
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.
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
Use widths, alignment and decimal places to print a tidy receipt.
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
What does f'{0.256:.1%}' produce?
Summary
- Put an expression in curly brackets, and add
:specto control how it looks. .2fsets 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.