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

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?

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

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

Building a learner message

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

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

Supply the arguments: The first argument is 98 and the second argument is beginner.

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

selectsselects{0}first placeholderAdafirst argument{1}second placeholder42second argument
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.

Reordering supplied values

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

Assign positions: The city occupies position 0 and the country occupies position 1.

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

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

thenthenthen0argument position>right alignment10field width.2fdecimal presentation
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.

precisionalignment and padding3.14159unformatted value3.14two decimal places3.14right-aligned field
How do precision, alignment, and padding specifications change the appearance and size of a substituted value?

Formatting a measurement

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

Select the value: Use the placeholder for the argument that contains the measurement.

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

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

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

Mistakes Beginners Make

  • Assuming placeholders always use the next argument from left to right

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

    Fix: Treat {0} as the first argument and {1} as the second argument wherever they appear.

  • Forgetting that empty braces use argument order

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

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

  • Trying to concatenate a non-string value directly

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

    Fix: Use format(), which automatically converts supplied values to strings, or explicitly apply str() when concatenating.

  • Treating a formatting specification as ordinary message text

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

    Fix: 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. format() fills curly-brace placeholders in a template with supplied argument values.
  2. Numbered placeholders such as {0} and {1} select arguments by positional index, while empty braces use argument order.
  3. Formatting 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 explicit str() calls for non-string values.
  5. A template is usually clearer and more maintainable than manually joining fixed text and variable data.

Key Takeaways

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