Hone

Lessons · Python · putting values into text

Putting values into text

f"...{value}..." drops a value into a string where the braces are, with optional formatting after a colon.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every message, label, receipt line, log entry and filename is text with values in it. f-strings are the clean way, and the format specs handle money, padding and dates.

How to think about it

Where do the values go, and how should each look? Write the sentence you want, then replace each value with {name}. For numbers that need shaping, add :.2f for two decimals, :>8 to right-align in 8 spaces, :, for thousands separators.

Worked example

name, total = "Ada", 1234.5
Two values.
print(f"{name}: {total:,.2f}")
Ada: 1,234.50. The colon starts the format: commas, two decimals.
print(f"{name:<6}|{total:>10.1f}|")
Ada | 1234.5|. Left-align in 6, right-align in 10.

Your turn

Show a percentage with one decimal place.

share = 0.4567
print(f"{share * 100:}%")

The trap

Forgetting the f. "Hello {name}" prints the braces literally, and nothing warns you.

Practise putting values into text on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.