Concepts / Type Conversion

Type Conversion

The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.

  • Programming

From Template to Message

A message often contains both fixed text and changing data. The format() method lets you write the fixed text as a template and mark the locations where values should appear. It then constructs a new string by substituting argument values into those locations.

python
Output
My name is Swaroop and I am 20 years old.
{0}{1}substitutesubstituteTemplate string"My name is {0} and I am{1} years old."SwaroopFinal stringMy name is Swaroop and I am20 years old.20
What happens to the template string as each placeholder is replaced by its argument?

Matching Placeholders to Arguments

The basic syntax is string.format(arguments). The string before format() contains the template and its placeholders. The values inside format() are the arguments that fill those placeholders. A placeholder can contain a positional index, such as {0} or {1}, which identifies the argument to use.

selectsselectsinsertinsert{0}first argumentSwaroopargument 0name location{1}second argument20argument 1age location
How does each positional index such as {0} or {1} select and place the corresponding argument?

Python counts positions from zero. Therefore, {0} refers to the first argument, {1} refers to the second argument, and later indices refer to later arguments. The index controls both which value is selected and where that value appears in the template.

python
Output
B comes after A.

Using Implicit Positions

The numbers inside placeholders are optional. Empty braces, written as {}, are filled from left to right with the arguments supplied to format(). This produces the same ordering as explicit indices when the arguments should appear in their original order.

python
Output
My name is Swaroop and I am 20 years old.
{opens field0argument index:starts specificationformat_specdisplay instructions}closes field
What does each part of a placeholder control?

Controlling the Display

A formatting specification is placed after a colon inside a placeholder. The general form is {index:format_spec}. The index identifies the argument, while format_spec describes how that argument should appear in the resulting string. Specifications can control decimal precision, padding, and alignment.

python
Output
The result is 0.333

In {:.3f}, the .3f specification formats the value as a float and displays three digits after the decimal point. The value produced by 1.0 / 3 is displayed as 0.333 instead of showing its longer decimal representation.

python
Output
___hello___

In {0:_^11}, the underscore is the padding character, the caret centers the value, and 11 is the total width. Because hello has five characters, three underscores are placed on each side to produce a width of eleven characters.

containscontainscontainscontainspadspositionssizes{0:_^11}complete placeholder0selects argument 0___hello___eleven characters_padding character^center alignment11total width
How does a formatting specification change a value's precision, spacing, alignment, or padding?

Why Templates Beat Concatenation

ApproachHow values are combinedMain consideration
String concatenationJoins pieces with the plus operatorNon-string values require explicit str() calls
format()Substitutes values into placeholdersAutomatically converts values to strings

Concatenation with the plus operator can become visually cluttered and error-prone. It also requires explicit conversion of non-string values with str(). With format(), the template and the data are separate: the message can be changed without changing the variables, and values are automatically converted to strings.

python
python

Mistakes with format()

  • Treating the first argument as index 1

    Python counts positional arguments from zero, so the first argument has index 0 and the second has index 1.

    Fix: Use {0} for the first argument and {1} for the second argument.

  • Assuming empty braces can select arguments in a custom order

    Empty braces consume arguments from left to right.

    Fix: Use explicit indices such as {1} and {0} when the output order differs from the argument order.

  • Expecting a formatting specification to be ordinary text

    The part after the colon is an instruction controlling how the selected value is displayed.

    Fix: Read the placeholder as an index followed by a formatting specification.

  • Concatenating a numeric value without conversion

    Concatenation with + requires non-string values to be explicitly converted with str().

    Fix: Use "Age: {}".format(20), or explicitly convert the value before concatenating.

Practice the Mapping

What do you think happens?

What output is produced by "{1} and {0}".format("red", "blue")?

  • red and blue
  • blue and red
  • {1} and {0}
  • An output with the values in argument order
Reveal answer

Answer: blue and red

{1} selects the second argument, blue, and {0} selects the first argument, red.

EASY

Rewrite this message using format() instead of concatenation: "Name: " + str("Swaroop") + ", Age: " + str(20). Then decide whether positional indices or empty braces make the template clearer.

Hints
  • Put the fixed text and placeholders in one string.
  • Use one argument for the name and one argument for the age.
  • Empty braces work when the values appear in the same order as the arguments.

Reading a Formatted Placeholder

Explain the parts of {0:_^11}.

Select the value: The index 0 selects the first argument supplied to format().

Choose padding: The underscore specifies the character used for empty positions.

Choose alignment: The caret centers the selected value within the available width.

Set the width: The number 11 specifies a total field width of eleven characters.

When the selected value is hello, the result is ___hello___ because three underscores are added on each side.

Key Takeaways

  1. format() constructs a string by replacing placeholders with argument values.
  2. Positional indices start at 0: {0} selects the first argument and {1} selects the second.
  3. Empty braces insert arguments from left to right.
  4. A colon introduces a formatting specification for precision, padding, or alignment.
  5. format() automatically converts values to strings and is usually clearer than manual concatenation when fixed text and variable data are combined.

Key Takeaways

  • format() uses a template string containing placeholders and arguments that supply their values.
  • Explicit indices map placeholders to arguments, while empty braces use arguments from left to right.
  • Formatting specifications after a colon control how values are displayed.
  • format() automatically converts values to strings and keeps message text separate from the data.
  • Use format() when a readable message combines fixed text with variable values.