Decimals in f-strings
A division can give a number with many decimals, and printing it shows them all:
total = 10
people = 3
share = total / people
print(f"Each pays {share}")
Each pays 3.3333333333333335An f-string can say how a value should be shown. After the value inside the curly braces, write a colon and a format specifier. .2f means "as a decimal number with 2 decimals":
total = 10
people = 3
share = total / people
print(f"Each pays {share:.2f}")
print(f"Exactly: {share:.5f}")
print(f"Roughly: {share:.0f}")
Each pays 3.33
Exactly: 3.33333
Roughly: 3The number before the f is the number of decimals, and the last decimal is rounded: 2/3 with .2f is 0.67. The f stands for a float, a number with a decimal point. The value itself doesn't change: only the way it's shown.
The specifier adds decimals too, which is handy for prices. A whole number gets zeros after the point:
price = 4
discount = 0.5
print(f"{price:.2f} {discount:.2f} {price - discount:.2f}")
4.00 0.50 3.50The last value shows that a calculation can go inside the braces too, with the specifier after it.
An f-string is a string
An f-string doesn't have to go straight to print. It makes an ordinary string, which you can store in a variable, join with other strings or return from a function:
def receipt_line(item: str, price: float) -> str:
return f"{item}: {price:.2f}"
line = receipt_line("Tea", 2.5)
print(line)
print(receipt_line("Cake", 3.75) + " (today's special)")
print(len(line))
Tea: 2.50
Cake: 3.75 (today's special)
9receipt_line returns the formatted text, and the code that calls it decides what to do with it. len(line) shows that line is an ordinary string of 9 characters.