Concepts / Type Conversion

Type Conversion

format() is especially useful when a message combines fixed text with variable data of different types.

  • 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 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.
Template string"My name is {0} and I am{1} years old."SwaroopFinal stringMy name is Swaroop and I am20 years old.20{0}{1}substitutesubstitute
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.

{0}first argumentSwaroopargument 0name location{1}second argument20argument 1age locationselectsselectsinsertinsert
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.

{0:_^11}complete placeholder0selects argument 0___hello___eleven characters_padding character^center alignment11total widthcontainscontainscontainscontainspadspositionssizes
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

Comparison of the two string-building approaches described in the source.

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()

  • Common mistake

    Treating the first argument as index 1

    What it looks like
    "{1} then {2}".format("first", "second")
    Why it fails

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

    Do this instead

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

  • Common mistake

    Assuming empty braces can select arguments in a custom order

    What it looks like
    "{} then {}".format("first", "second")
    Why it fails

    Empty braces consume arguments from left to right.

    Do this instead

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

  • Common mistake

    Expecting a formatting specification to be ordinary text

    What it looks like
    "{0:.3f}".format(1.0 / 3)
    Why it fails

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

    Do this instead

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

  • Common mistake

    Concatenating a numeric value without conversion

    What it looks like
    "Age: " + 20
    Why it fails

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

    Do this instead

    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.
Worked example

Reading a Formatted Placeholder

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

  1. 1
    Select the value

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

  2. 2
    Choose padding

    The underscore specifies the character used for empty positions.

  3. 3
    Choose alignment

    The caret centers the selected value within the available width.

  4. 4
    Set the width

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

Result

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

Key Takeaways

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

At a glance

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

More concepts starting with T