Formatting with f-strings
Scenario: A status line must combine names, counts, and a decimal percentage.
New words, in plain English
- f-string - a string prefixed with f that evaluates expressions inside braces
- Format specifier - instructions after
:controlling display - Escape sequence - a special character such as `
` for a new line
F-strings keep values beside their labels. Use :.2f for two decimal places and alignment specifiers for reports. Raw strings prefixed r are useful for regex and Windows-like paths.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
service = "api"
healthy = 9
total = 10
print(f"{service}: {healthy / total:.1%} healthy")
Tip: Formatting changes display, not the underlying numeric value.
Goal: Practice this idea in the py-string-manipulation challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.