Lesson · Strings & Text
String Formatting
60 min readString Formatting
String formatting turns values into readable text for users, logs, and reports. Modern Python uses f-strings for direct formatting and, in Python 3.14, t-strings for custom processing of interpolated templates.
Learning goals
- Read a specifier such as
:<10or:>8.2fand say which parts control fill, alignment, width, and precision. - Format the same value as a fixed-point number, a percentage, and scientific notation without touching the stored value.
- Use the
=debug form and explain what it adds to the rendered output. - Choose between f-strings,
str.format(), and%formatting based on when the template is known and who supplies the values. - State what a t-string produces instead of text and why an intermediate component would want that object.
Mental model
Formatting is a rendering step, never a storage step: the mini-language decides how a value appears, and the value itself is untouched. An f-string renders as soon as it evaluates, while a t-string hands the static parts and interpolation objects to another component that can validate, escape, or transform them before text is produced.
The spec decides how a value appears
render time only: the value is untouched
Mental model
the same mechanism as a compact list
f"...{expr:spec}..." evaluates now, renders text immediately
↓ everything after ":" [[fill]align][width][,][.precision][type]
↓ width is a minimum longer values widen the field, they are never cut
t"..." (3.14) same interpolation syntax, stops one step earlier
↓ produces a Template template.strings and template.values stay inspectableVersion note
Python 3.14 adds template string literals (t"...") and string.templatelib. Earlier Python versions do not support t-string syntax.
Core idea
An f-string embeds expressions directly in text and renders them on the spot, delegating layout to the format mini-language: the part after : controls alignment, width, precision, signs, separators, and type-specific rendering. Because rendering produces text and nothing else, the stored value keeps its full precision, so formatting and rounding are separate decisions. Python 3.14's t-strings reuse the same interpolation syntax but produce a Template, which lets another component inspect or transform the parts before any text exists.
f-strings
An f-string evaluates expressions and immediately produces a str. Format specifications after : control representation such as width, alignment, precision, and numeric style.
Format specifiers
The format mini-language controls alignment, sign, width, precision, separators, and type-specific rendering. The same syntax is used by f-strings and format().
Alignment
Format alignment controls how a rendered value occupies a field: left, right, or centered. It matters when building human-readable tables and fixed-width output.
Width
A format width is a minimum field width, not a maximum string length. Values wider than the requested width are not truncated automatically.
Precision
Format precision has type-dependent meaning, commonly controlling decimal places for floating-point formatting. Formatting changes the representation, not the underlying stored numeric value.
Numeric formatting
Numeric format specifiers can render percentages, fixed-point values, scientific notation, base representations, grouping separators, and signs without changing the stored number.
Debug expressions
An f-string expression with = includes both the expression text and its value, which is useful during debugging. Explicit format or conversion specifiers can still be added.
str.format()
str.format() applies the same format mini-language through method calls. F-strings are usually clearer for local expressions, while str.format() remains useful in some dynamic-template code.
% formatting as legacy syntax
Percent-style formatting predates str.format() and f-strings. You still encounter it in older code and some logging patterns, but new application formatting usually favors modern alternatives.
Template string literals (t-strings, Python 3.14)
A t-string uses syntax similar to an f-string but produces a template object instead of rendering directly to text. This lets another component safely inspect or transform literal and interpolated parts before final rendering.
string.templatelib.Template and interpolation objects
string.templatelib.Template exposes the static string segments and interpolation objects produced by a t-string. It is useful for custom escaping, structured templating, and domain-specific rendering.
When t-strings are preferable to immediately-rendered f-strings
Use t-strings when an intermediate component must inspect, validate, escape, or transform interpolated values before rendering. Use f-strings when immediate plain-text formatting is exactly what you need.
Python 3.14 example: t-strings
Unlike an f-string, this expression produces a template object whose static and interpolated parts can be processed before final rendering.
from string.templatelib import Interpolation name = "Ada" score = 98 template = t"Student {name} scored {score:.1f}" print(template.strings) print(template.values) for part in template: if isinstance(part, Interpolation): print("expression:", part.expression) print("value:", part.value)
Common mistakes
- Using formatted output as if it changed the stored number:
f"{price:.2f}"renders text with two decimals whilepricekeeps every digit, so rounding that matters to later arithmetic belongs outside the format call. - Building a format string from user input: templates are interpreted, so a format string assembled from untrusted text can raise errors or reach into objects; keep the template a literal and pass values as arguments.
- Treating a t-string as text:
t"..."produces aTemplate, not astr, so string operations fail until the parts are rendered deliberately; use an f-string when immediate text is the goal. - Assuming a width truncates: widths are minimums, so a longer value widens the field and shifts whatever follows it, which quietly breaks column alignment in reports.
Practice: Easy
- Print the worked example's first line as written, then swap the two alignment markers (
:>10and:<8.2f) and describe how the layout changes. - Run
f"{price = }"andf"{price = :.3f}"and label which output characters are literal text and which are the rendered value. - Format
0.5three ways, as{:.0%},{:.2f}, and{:.1e}, and name the representation each specifier selects.
Practice: Medium
- Build a five-row table from a list of
(name, score)pairs using:<12and:>6.1f; add one name longer than twelve characters and explain what happens to the column. - Show that formatting does not mutate: keep a total, print it with
:.2f, then print it again without a specifier and explain why display and value can disagree. - Write one message three ways, as an f-string, as a
str.format()call with named fields, and as%formatting; state which form you would keep in new code and which remains useful for compatibility.
Practice: Hard
- Design a report formatter over records with amounts and a rate: aligned columns, a thousands separator, a sign for negatives, and two decimals, all from the mini-language. Define the expected output for a negative amount and a missing value, and one test, before implementing.
- Build a failure lab with three cases: an invalid specifier such as
{price:.2f.3f}, a specifier whose type code does not fit the value such as{name:.2f}, and a format string assembled at runtime from user input; explain the mechanism behind each failure. - Connect this lesson to the Unicode lesson: explain why a template object that can escape or transform interpolated values before rendering is safer than an f-string that produces final text immediately.
Lesson checklist
- I can read a format specifier and name the parts that control alignment, width, and precision.
- I can render one value as fixed point, a percentage, and scientific notation without changing the stored value.
- I can use the
=debug form and say what it adds to the output. - I can explain what a t-string produces and when that beats immediate rendering.
Remember
Formatting turns values into presentation text through the mini-language after `:`, and it never changes the value it renders, which keeps rounding for display separate from rounding for storage. F-strings render immediately, `str.format()` and `%` remain compatible alternatives for template-style code, and Python 3.14's t-strings produce a `Template` so another component can inspect or escape the interpolated parts before any final text is produced.
Interview angles
What is the main purpose of **f-strings**?+
An f-string evaluates expressions and immediately produces a str. Format specifications after : control representation such as width, alignment, precision, and numeric style.
What should you pay attention to when using **Format specifiers**?+
The format mini-language controls alignment, sign, width, precision, separators, and type-specific rendering. The same syntax is used by f-strings and format().
How does **Alignment** fit into this lesson?+
Format alignment controls how a rendered value occupies a field: left, right, or centered. It matters when building human-readable tables and fixed-width output.
Why can a longer value break a column that specifies `:>8`?+
The width is a minimum field size, so values up to eight characters are padded to eight while longer ones are never truncated; they widen the field and push the rest of the line. Aligned tables must account for the longest value, or accept the drift.