Formatting
f-strings, decimal places and alignment.
Gluing text and numbers together with + is awkward: "Age: " + 30 gives a TypeError, because a string and a number cannot be added. You need str(30), or an f-string. Put f before the quote and write any expression inside curly braces:
name = "Ada"
age = 36
print(f"{name} is {age}, next year {age + 1}")
After a colon inside the braces you give the format:
price = 3.14159
print(f"{price:.2f}") # 3.14
print(f"{7:03d}") # 007
print(f"{1234567:,}") # 1,234,567
print(f"[{'ok':>5}]") # [ ok]
Here that is two digits after the point, a width of 3 padded with zeros, a thousands separator and right alignment within a width of 5. < aligns to the left and ^ to the centre. With these formats the columns of a report line up without counting spaces by hand.
A handy debugging trick is the = sign after an expression: f"{price=}" prints price=3.14159, both the name and the value.
In older code you will meet "%s and %d" % (a, b) and "{} and {}".format(a, b). You need to be able to read them, but new code is easier to write with f-strings. One limitation: in Python 3.11 an expression inside an f-string cannot use the same quotes as the string around it. If the string is in double quotes, use single quotes inside the braces.
Practice
Two digits
What does the program print?
price = 3.14159 print(f"{price:.2f}")A string and a number
What happens when you run print("Age: " + 30)?
- A TypeError
- It prints Age: 30
- It prints Age: 30.0
- A SyntaxError before the program starts
A receipt line
Write a function line(name, price) that returns a string of the form name: price, where the price is always shown with two digits after the point. For example, line('tea', 45.5) returns tea: 45.50.