Showing a result is not only about being correct: how it looks matters too. Python offers formatted strings, or f-strings, to insert values inside a text and control their appearance.
f-strings
You write an f right before the quotes and put the values or expressions between curly braces:
a = 2
b = 3
name = "Ana"
print(f"{a} + {b} = {a + b}") # 2 + 3 = 5
print(f"Hello, {name}") # Hello, Ana
Fixed decimals
After a colon you give the format. .2f means 2 decimals in a decimal number:
pi = 3.14159
print(f"{pi:.2f}") # 3.14
print(f"{pi:.0f}") # 3
print(f"{2:.2f}") # 2.00 (it also adds zeros)
Using round() and :.2f is not the same: round() changes the value, :.2f only changes how it is displayed and always writes the requested decimals.
Widths and alignment
To align columns you give a width: < aligns left, > aligns right and ^ centers.
name = "Ana"
price = 3.5
print(f"{name:<10}|{price:>8.2f}|") # Ana | 3.50|
print(f"{name:>10}|{name:^10}|") # Ana| Ana |
Other useful formats
| Format | Result | Example |
|---|---|---|
:, | Thousands separator | f"{1234567:,}" → 1,234,567 |
:05d | Integer with leading zeros | f"{42:05d}" → 00042 |
:.1% | Percentage | f"{0.256:.1%}" → 25.6% |
The options of print()
print() accepts two parameters to control the text: sep (what goes between values) and end (what goes at the end, a line break by default):
print("a", "b", "c", sep="-") # a-b-c
print("1", "2", "3", sep="") # 123
print("Hello", end="")
print("!") # Hello!
Other ways to format
There is also the format() method: "{} is {} years old".format("Ana", 25). It does the same as an f-string, but f-strings are shorter and more readable, so they are the recommended option.
Practice in the exercise about the formatted invoice.