Python · Lesson 1.4

f-strings

Put values into text and format numbers as money, percentages and tidy columns.

1Values inside text

Put an f before the quotes, and anything in {} gets replaced by its value. This is the cleanest way to build text from variables.

name = "Ben"
orders = 7
print(f"{name} placed {orders} orders")
Python

Practice

Use an f-string to print Lisbon had 1200 visitors from the two variables.

city = "Lisbon"
visitors = 1200
# Print the sentence with an f-string
Python

2Expressions inside the braces

The braces can hold any expression, not just a name. Python works it out first, then puts the result in the text.

price = 4.5
qty = 3
print(f"Total: {price * qty}")
Python

Practice

Print Conversion: 0.25 by dividing buyers by visitors inside the braces.

buyers = 50
visitors = 200
# Print the conversion with an f-string
Python

3Formatting numbers

After a colon you can say how to show a number. :.2f gives 2 decimals, :, adds thousands separators, and :.1% shows a percentage.

revenue = 1234567.891
rate = 0.0837
print(f"{revenue:,.2f}")
print(f"{rate:.1%}")
Python

Practice

Print Revenue: $48,250.50 and, on the next line, Margin: 31.2%, using the variables below and format codes.

revenue = 48250.5
margin = 0.3124
# Two f-strings
Python

4Lining things up

:<10 pads text to 10 characters on the left side and :>8 pads on the right, which makes neat columns.

print(f"{'Item':<10}{'Price':>8}")
print(f"{'Tea':<10}{3.5:>8.2f}")
print(f"{'Biscuits':<10}{12:>8.2f}")
Python

Practice

Print one line with name padded to 8 characters on the left, followed by score right-aligned in 5 characters. The output should be Mei 92 (the name, padding, then the number).

name = "Mei"
score = 92
# One f-string with padding
Python