Code

F-Strings

Gluing with + and str() gets messy fast. f-strings are the modern way: put an f before the quotes and drop any value straight in with {curly braces}:

name = "Pip"
gold = 7
print(f"{name} has {gold} gold")   # Pip has 7 gold
print(f"Double: {gold * 2}")        # Double: 14

Add a format spec after a colon to control how it looks:

Spec Meaning Example Result
:.2f 2 decimal places f"{3.14159:.2f}" 3.14
:>6 right-align in 6 spaces f"[{'hi':>6}]" [ hi]
:<6 left-align f"[{'hi':<6}]" [hi ]
:^6 centre f"[{'hi':^6}]" [ hi ]
:03 pad with zeros f"{7:03}" 007

No more str() needed: f-strings turn numbers into text for you.

Assignment

Print a shop receipt using f-strings. First set total to qty times price. Then print exactly:

Item: Lantern oil
Quantity: 3
Total: 13.50 gold
[  Lantern oil  ]

The last line is item centred in a width of 15, between square brackets.