String Formatting and the format() Method
The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.
Try it: Format spec mini-language
How Python reads a format spec like *^+14,.2f in f-strings, str.format() and format(): fill, align, sign, #, 0, width, grouping, precision and type — and how it then builds the output, rounding floats exactly the way Python does.
How it works
- Parse the spec left to right: [[fill]align][sign][z][#][0][width][,|_][.precision][type].
- Check the pieces against the value's type (int, float, str); invalid combinations raise the same ValueError Python raises.
- Turn the value into digits: ints in base 10/16/2/8; floats rounded half-to-even on their exact binary value (so 2.675 → 2.67).
- Add the sign, 0x/0b/0o prefix, thousands separators and the decimal point or exponent.
- Pad with the fill character to the width: left, right, centred, or between the sign and the digits (=).
Default run (18 steps): format(-1234.5678, '*^+14,.2f') — same as f"{-1234.5678:*^+14,.2f}". Read the spec from left to right. … format(-1234.5678, '*^+14,.2f') → '**-1,234.57***' (14 characters).
Simplified: int, float and str values only (no custom __format__, no locale-dependent 'n' grouping); width up to 60 and precision up to 50.
Loading the simulation…
From Values to Messages
When a message combines fixed text with changing data, you need a reliable way to place each value in the right location. The format() method lets you write the message as a template first, then substitute actual argument values into marked locations. This avoids manually joining separate pieces with the plus operator.
The format() method constructs a string by replacing placeholders in a template with corresponding argument values. Its basic form is a template string followed by .format(arguments).
What do you think happens?
A template contains two empty placeholders and format() receives two arguments. Which argument fills the first placeholder?
Reveal answer
The first argument
Empty braces fill arguments in order, so the first empty placeholder uses the first argument and the second empty placeholder uses the second argument.
Following the Substitution
Think of format() as processing a template. It finds each specification, identifies the argument assigned to that specification, converts the value into string form, and places the result at that location. The fixed text remains part of the template while the placeholder locations receive the supplied values.
Building a learner message
Place the value 98 into the score location and the value beginner into the level location.
- 1Write the template
The fixed words stay in the string, while {0} and {1} mark the two substitution locations.
- 2Supply the arguments
The first argument is 98 and the second argument is beginner.
- 3Match locations
The first placeholder receives 98 and the second placeholder receives beginner.
The completed message is Score: 98, level: beginner.
Choosing Argument Positions
A specification is a pair of curly braces that can be empty or can contain a number or name identifying the argument to use. Numbered placeholders use zero-based positional indices: {0} refers to the first argument, {1} refers to the second argument, and so on. Empty braces use the arguments in their supplied order.
Numbered placeholders are useful when the order of appearance in the message differs from the order in which values were supplied. For example, a template can place {1} before {0}; each placeholder still selects its numbered argument rather than simply taking the next value from left to right.
Reordering supplied values
Use the first argument as a city and the second argument as a country, but display the country before the city.
- 1Assign positions
The city occupies position 0 and the country occupies position 1.
- 2Arrange placeholders
Place {1} first in the template and {0} second.
- 3Read the result
The country appears first even though it was supplied as the second argument.
A template such as {1}, {0} can display the second argument before the first.
Controlling Appearance
A placeholder can include a formatting specification after a colon. These specifications control how the substituted value appears, including decimal precision, alignment, and padding. This lets the template control presentation without requiring manual string manipulation.
In the specification {0:>10.2f}, the 0 selects the first argument. The remaining specification controls the displayed form: > requests right alignment, 10 provides a field width, and .2f requests a fixed-point display with two digits after the decimal point. The important idea is that the value and its presentation rule are kept together inside the placeholder.
Formatting a measurement
Display a measurement with three digits after the decimal point and place it in a left-aligned field of width 20.
- 1Select the value
Use the placeholder for the argument that contains the measurement.
- 2Set precision
Use a specification such as :.3f to control the decimal precision.
- 3Set alignment and padding
Use a specification such as :<20 to left-align the value and provide the requested field width.
The template controls both the number of displayed decimal places and the space used for the value.
Why Formatting Beats Concatenation
String concatenation joins pieces with the plus operator, but non-string values must be converted explicitly with str() before they can be joined. format() automatically converts supplied values to strings while placing them into the template. As a result, format() keeps the message structure in one readable template and avoids some of the error-prone manual joining required by concatenation.
| Concern | format() | Concatenation with + |
|---|---|---|
| Message structure | Kept in a template string | Split across separately joined pieces |
| Non-string values | Converted automatically | Require explicit str() calls |
| Presentation rules | Can be placed in specifications | Require manual string manipulation |
| Best fit | Messages combining fixed text and variable data | Simple joining when all pieces are already strings |
The source pack contrasts format() with manual concatenation.
f-Strings: The Same Idea, Written Inline
Added by the IKSHA team to go beyond the source course material.
Since Python 3.6 a string that starts with the letter f can hold expressions directly between the curly braces. Python evaluates each expression and places the result in the string, so the value no longer has to be passed as a separate argument. The text after a colon is the same formatting specification that format() uses.
Notebook: 3 x 4.50
Notebook: 3 x 4.50- The first line uses
format()with numbered placeholders - The second line is an f-string: the names sit inside the braces
- Both lines print the same text because :.2f means two digits after the decimal point
Because the braces hold real expressions, you can calculate inside them, and the specification still follows the colon.
13.50
qty=3
1,234,567.89
25.6%- An expression such as qty * price is evaluated before it is formatted
- A trailing = prints the expression and its value, which is handy when debugging
- A comma in the specification groups thousands
- A % in the specification multiplies by 100 and adds the percent sign
Alignment and Width, With Values You Choose
Added by the IKSHA team to go beyond the source course material.
The specification after the colon works the same in f-strings and in format(): an optional alignment (<, > or ^), a width, and a type such as f for fixed-point or d for whole numbers. A leading 0 pads numbers with zeros. The width itself can come from a variable by putting it in its own braces.
| 4.50|
|Notebook |
| 3 |
|00003|
| 4.50|- > right-aligns in a field 10 characters wide
- < left-aligns in a field 12 characters wide
- ^ centres in a field 7 characters wide
- 05d pads a whole number with zeros to width 5
- {w} inside the braces takes the width from the variable w
Choosing between the two forms is mostly about where the values live. Use an f-string when the values are already in variables next to the text. Use format() when the template is stored apart from the data, for example a message kept in one place and filled in from several others, because the template is then an ordinary string that can be passed around before any values exist.
Mistakes Beginners Make
Common mistake Assuming placeholders always use the next argument from left to right
What it looks likeA template uses {1} before {0}.Why it failsNumbered placeholders select arguments by their indices, so their visual order does not determine which value they receive.
Do this insteadTreat {0} as the first argument and {1} as the second argument wherever they appear.
Common mistake Forgetting that empty braces use argument order
What it looks likeA template contains two empty placeholders but the arguments are expected to appear in a custom order.
Why it failsEmpty braces fill arguments in order and do not express a custom rearrangement.
Do this insteadUse numbered placeholders when the displayed order differs from the supplied order.
Common mistake Trying to concatenate a non-string value directly
What it looks likeFixed text is joined with a numeric value using the plus operator without an explicit conversion.
Why it failsConcatenation with + requires explicit
str()calls for values that are not already strings.Do this insteadUse format(), which automatically converts supplied values to strings, or explicitly apply str() when concatenating.
Common mistake Treating a formatting specification as ordinary message text
What it looks likeA precision or alignment rule is placed outside the placeholder.
Why it failsFormatting specifications belong inside the curly-brace placeholder after a colon.
Do this insteadKeep the argument selection and its presentation rule together inside the placeholder.
Practice the Mapping
Design a template for a message that displays a product name, a quantity, and a price. Use positional indices so the product name appears first, the quantity appears second, and the price appears third. Then decide which specification would be useful if the price must show controlled decimal precision.
Hints
- Use {0}, {1}, and {2} to identify the three argument positions.
- Remember that positional indices begin with 0.
- A fixed-point precision specification can control the number of displayed decimal places.
Explain why format() is a better choice than concatenation for a message that combines fixed wording, a numeric value, and an alignment requirement.
Hints
- Consider whether concatenation automatically converts the numeric value.
- Consider where the message structure and alignment rule are expressed.
- Use the comparison between automatic conversion and explicit
str()calls.
Key Takeaways
- 1
format()fills curly-brace placeholders in a template with supplied argument values. - 2Numbered placeholders such as {0} and {1} select arguments by positional index, while empty braces use argument order.
- 3Formatting specifications after a colon control presentation features such as decimal precision, alignment, and padding.
- 4
format()automatically converts values to strings, while concatenation with + requires explicitstr()calls for non-string values. - 5A template is usually clearer and more maintainable than manually joining fixed text and variable data.
At a glance
- The
format()method replaces placeholders in a template with argument values. - Positional indices map placeholders to specific arguments and allow values to be displayed in a different order.
- Specifications inside placeholders control precision, alignment, and padding.
format()automatically converts values to strings and is often clearer than manual concatenation.