String Concatenation
The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.
From Pieces to Templates
When a message combines fixed text with variable data, you need a way to place each value in the correct location. One approach is to join separate pieces with the plus operator. The format() method provides another approach: write the complete message as a template, mark insertion points with curly braces, and then supply the values that belong in those positions.
Following the Substitution
name = "Swaroop" age = 20 message = "Hello, {0}! You are {1}.".format(name, age) print(message)
The basic form is string.format(arguments). The string before .format() is the template. Its curly-brace specifications identify locations where argument values should be inserted. After substitution, format() produces a string containing the original fixed text and the inserted values.
Mapping Arguments by Position
Reading explicit indices
Determine which values fill {0} and {1} in "Hello, {0}! You are {1}.".format(name, age).
Identify the arguments: The arguments are name and age, supplied in that order.
Apply Python's indexing: Python counts from 0. Therefore name is argument 0 and age is argument 1.
Substitute the values: {0} receives the value of name, and {1} receives the value of age.
The resulting message is Hello, Swaroop! You are 20.
Hello, Swaroop! You are 20.
Hello, Swaroop! You are 20.Numbered placeholders are optional when values are inserted from left to right. Empty braces fill arguments in order: the first {} uses the first argument, the second {} uses the second argument, and so on. Explicit indices are useful when you want to change the order or reuse an argument more than once.
Controlling Display Details
A format specification is placed after a colon inside the braces. The general form is {index:format_spec}. The index identifies the argument, while format_spec describes how that argument should appear. Specifications can control decimal precision, padding, and alignment without manual string manipulation.
print("{0:.3f}".format(1.0 / 3)) print("{0:_^11}".format("hello"))
| Specification | Meaning | Source example |
|---|---|---|
| {0:.3f} | Use argument 0 as a float and show 3 digits after the decimal point | 1.0 / 3 becomes 0.333 |
| {0:_^11} | Center argument 0 in a width of 11 and use underscores as padding | hello becomes ___hello___ |
Two format specifications described in the source examples
Placeholders can also use keyword arguments instead of positional indices. In the example, {name} is filled by the keyword argument name='Swaroop', and {book} is filled by book='A Byte of Python'. This names the relationship between each placeholder and its value directly.
Choosing a Clearer Assembly Method
| Aspect | Plus concatenation | format() |
|---|---|---|
| Message construction | Joins separate pieces manually | Uses a template with placeholders |
| Non-string values | Requires explicit str() calls | Automatically converts values to strings |
| Readability | Can become visually cluttered | Keeps the message shape clear |
| Changing the message | May require editing several joined pieces | The template can be changed separately from the variables |
Mistakes Beginners Make
Treating the first argument as index 1
Python counts argument positions from 0, so the first argument is index 0 and the second argument is index 1.
Fix:
Read {0} as the first argument and {1} as the second argument.Using plus concatenation with a non-string value without conversion
Concatenation with plus requires non-string values to be explicitly converted with str().
Fix:
Use "Age: " + str(age), or use "Age: {}".format(age).Adding a format specification without the colon
The format specification comes after a colon inside the braces.
Fix:
Write "{0:.3f}" when selecting argument 0 and displaying three digits after the decimal point.Assuming empty braces can express a reordered argument
Empty braces consume arguments in order from left to right.
Fix:
Use explicit indices such as "{1} {0}" when the output order differs from the argument order.
Empty braces are convenient only when arguments should be inserted in the same order in which they are supplied. If an argument must appear more than once or the output order changes, use an explicit positional index or a keyword placeholder.
Practice the Mapping
What do you think happens?
What will this code print? name = "Swaroop" age = 20 print("{1} is {0} years old.".format(age, name))
Reveal answer
Answer: Swaroop is 20 years old.
{1} selects the second argument, name, while {0} selects the first argument, age. Positional indices refer to the order of arguments supplied to format().
Write a format() expression that produces the message Hello, Swaroop! You are 20. Use keyword placeholders rather than positional indices.
Hints
- Place {name} and {age} in the template.
- Supply name="Swaroop" and age=20 as keyword arguments to format().
Create a format() expression that displays 1.0 / 3 with three digits after the decimal point, then create another expression that centers hello in a width of 11 characters using underscores as padding.
Hints
- Use the specification :.3f for the decimal value.
- Use the specification :_^11 for centered underscore padding.
Key Takeaways
- format() builds a string by replacing curly-brace placeholders with supplied argument values.
- Numbered placeholders use zero-based positional indices: {0} refers to the first argument, {1} to the second, and so on.
- Empty braces insert arguments from left to right, while explicit indices support reordered or repeated values.
- A colon introduces a format specification, such as :.3f for decimal precision or :_^11 for centered padding.
- format() automatically converts values to strings and separates the message template from the data more clearly than manual plus concatenation.
Key Takeaways
- format() uses a template string and substitutes argument values into curly-brace placeholders.
- Positional indices begin at 0, so {0} selects the first argument and {1} selects the second.
- Empty braces fill arguments in order, while explicit indices allow reordering and reuse.
- Format specifications control presentation details such as decimal precision, alignment, and padding.
- Compared with plus concatenation, format() automatically converts values and keeps the message structure easier to read.