Concepts / String Formatting and the format() Method

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.

  • Programming
Interactive lab

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

  1. Parse the spec left to right: [[fill]align][sign][z][#][0][width][,|_][.precision][type].
  2. Check the pieces against the value's type (int, float, str); invalid combinations raise the same ValueError Python raises.
  3. 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).
  4. Add the sign, 0x/0b/0o prefix, thousands separators and the decimal point or exponent.
  5. 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.

Educational simulation

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.

Definition

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?

  • The first argument

  • The second argument

  • Both arguments

Reveal answer
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.

Template stringScore: {0}, level: {1}format()substitutionCompleted stringScore: 98, level: beginnerArguments98, beginnertemplatevaluessubstitutes
What happens to a template string as format() replaces each placeholder with an argument value?
Worked example

Building a learner message

Place the value 98 into the score location and the value beginner into the level location.

  1. 1
    Write the template

    The fixed words stay in the string, while {0} and {1} mark the two substitution locations.

  2. 2
    Supply the arguments

    The first argument is 98 and the second argument is beginner.

  3. 3
    Match locations

    The first placeholder receives 98 and the second placeholder receives beginner.

Result

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.

{0}first placeholderAdafirst argument{1}second placeholder42second argumentselectsselects
How does each numbered placeholder connect to the corresponding argument supplied to format()?

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.

Worked example

Reordering supplied values

Use the first argument as a city and the second argument as a country, but display the country before the city.

  1. 1
    Assign positions

    The city occupies position 0 and the country occupies position 1.

  2. 2
    Arrange placeholders

    Place {1} first in the template and {0} second.

  3. 3
    Read the result

    The country appears first even though it was supplied as the second argument.

Result

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.

0argument position>right alignment10field width.2fdecimal presentationthenthenthen
What does each part of a placeholder such as {0:>10.2f} control?

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.

3.14159unformatted value3.14two decimal places3.14right-aligned fieldprecisionalignment and padding
How do precision, alignment, and padding specifications change the appearance and size of a substituted value?
Worked example

Formatting a measurement

Display a measurement with three digits after the decimal point and place it in a left-aligned field of width 20.

  1. 1
    Select the value

    Use the placeholder for the argument that contains the measurement.

  2. 2
    Set precision

    Use a specification such as :.3f to control the decimal precision.

  3. 3
    Set alignment and padding

    Use a specification such as :<20 to left-align the value and provide the requested field width.

Result

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.

Concernformat()Concatenation with +
Message structureKept in a template stringSplit across separately joined pieces
Non-string valuesConverted automaticallyRequire explicit str() calls
Presentation rulesCan be placed in specificationsRequire manual string manipulation
Best fitMessages combining fixed text and variable dataSimple 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.

python
Output (expected)
Notebook: 3 x 4.50
Notebook: 3 x 4.50
Notes on the code
  • 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.

python
Output (expected)
13.50
qty=3
1,234,567.89
25.6%
Notes on the code
  • 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.

python
Output (expected)
|      4.50|
|Notebook    |
|   3   |
|00003|
|    4.50|
Notes on the code
  • > 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 like
    A template uses {1} before {0}.
    Why it fails

    Numbered placeholders select arguments by their indices, so their visual order does not determine which value they receive.

    Do this instead

    Treat {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 like

    A template contains two empty placeholders but the arguments are expected to appear in a custom order.

    Why it fails

    Empty braces fill arguments in order and do not express a custom rearrangement.

    Do this instead

    Use numbered placeholders when the displayed order differs from the supplied order.

  • Common mistake

    Trying to concatenate a non-string value directly

    What it looks like

    Fixed text is joined with a numeric value using the plus operator without an explicit conversion.

    Why it fails

    Concatenation with + requires explicit str() calls for values that are not already strings.

    Do this instead

    Use 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 like

    A precision or alignment rule is placed outside the placeholder.

    Why it fails

    Formatting specifications belong inside the curly-brace placeholder after a colon.

    Do this instead

    Keep the argument selection and its presentation rule together inside the placeholder.

Practice the Mapping

MEDIUM

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.
EASY

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. 1
    format() fills curly-brace placeholders in a template with supplied argument values.
  2. 2
    Numbered placeholders such as {0} and {1} select arguments by positional index, while empty braces use argument order.
  3. 3
    Formatting specifications after a colon control presentation features such as decimal precision, alignment, and padding.
  4. 4
    format() automatically converts values to strings, while concatenation with + requires explicit str() calls for non-string values.
  5. 5
    A 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.

Related concepts

More concepts starting with S