String Formatting
String formatting inserts values into text. An f-string is written with f before the opening quotation mark, and any expression inside braces is evaluated and inserted: f"{order_id}: {total:.2f}". The older str.format() method uses the same braces but takes the values as arguments, by position, by index, or by name, and appears throughout existing code. The oldest % style still exists in logging calls.
After a colon comes the format specification, which controls presentation rather than value. Common parts are a width, an alignment (< left, > right, ^ centered), a thousands separator (, or _), and a precision with a presentation type, such as .2f for two decimal places or .1% for a percentage. Width is a minimum, not a truncation limit: f"{'long-id':5}" keeps all seven characters. Wide Unicode characters can also disrupt terminal columns.
Formatting produces a new string and leaves the value unchanged: after f"{total:.2f}", total still holds all of its digits. The displayed figure is rounded from the stored binary float, not from the decimal literal you typed, so f"{2.675:.2f}" shows 2.67. When rounding must be part of the result rather than its display, round the value where it is computed, and use decimal arithmetic or integer minor units for money.
Two practical cautions: a literal brace inside an f-string is written {{ or }}, and text from an untrusted source should never be used as a format template, since a format string controls what gets read and rendered. For SQL, use query parameters instead of formatting values into the statement.
References: Formatted string literals, Format specification mini-language. See it in use in Python Strings, Conditions, and Loops.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
