Type Conversion
format() is especially useful when a message combines fixed text with variable data of different types.
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 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.
My name is Swaroop and I am 20 years old.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.
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.
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.
My name is Swaroop and I am 20 years old.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.
The result is 0.333In {:.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.
___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.
Why Templates Beat Concatenation
| Approach | How values are combined | Main consideration |
|---|---|---|
| String concatenation | Joins pieces with the plus operator | Non-string values require explicit str() calls |
| format() | Substitutes values into placeholders | Automatically 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.
Mistakes with format()
Common mistake Treating the first argument as index 1
What it looks like"{1} then {2}".format("first", "second")Why it failsPython counts positional arguments from zero, so the first argument has index 0 and the second has index 1.
Do this insteadUse {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 failsEmpty braces consume arguments from left to right.
Do this insteadUse 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 failsThe part after the colon is an instruction controlling how the selected value is displayed.
Do this insteadRead the placeholder as an index followed by a formatting specification.
Common mistake Concatenating a numeric value without conversion
What it looks like"Age: " + 20Why it failsConcatenation with + requires non-string values to be explicitly converted with
str().Do this insteadUse "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")?
Reveal answer
blue and red
{1} selects the second argument, blue, and {0} selects the first argument, red.
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}.
- 1Select the value
The index 0 selects the first argument supplied to
format(). - 2Choose padding
The underscore specifies the character used for empty positions.
- 3Choose alignment
The caret centers the selected value within the available width.
- 4Set 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. - 2Positional indices start at 0: {0} selects the first argument and {1} selects the second.
- 3Empty braces insert arguments from left to right.
- 4A 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.
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.