Type Conversion
The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.
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 |
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()
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")?
Reveal answer
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}.
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
- format() constructs a string by replacing placeholders with argument values.
- Positional indices start at 0: {0} selects the first argument and {1} selects the second.
- Empty braces insert arguments from left to right.
- A colon introduces a formatting specification for precision, padding, or alignment.
- 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.