String Concatenation
The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.
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 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)- 1The string contains two placeholders: {0} and {1}.
- 2
format(name, age)supplies two arguments. Python counts argument positions from 0, so name is argument 0 and age is argument 1. - 3
format()substitutes name into {0} and age into {1}. - 4The completed string is stored in message and printed.
Hello, Swaroop! You are 20.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).
- 1Identify the arguments
The arguments are name and age, supplied in that order.
- 2Apply Python's indexing
Python counts from 0. Therefore name is argument 0 and age is argument 1.
- 3Substitute 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"))- 1{0:.3f} selects argument 0, formats it as a float, and displays three digits after the decimal point.
- 2The value 1.0 / 3 produces a repeating decimal, which is displayed as 0.333 with this specification.
- 3{0:_^11} selects argument 0, centers it within a width of 11 characters, and uses underscores to fill the available space.
- 4The word hello has 5 characters, so 3 underscores are added on each side.
0.333
___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 |
Differences described in the source material
Mistakes Beginners Make
Common mistake Treating the first argument as index 1
What it looks like"{1} {0}".format("first", "second")Why it failsPython counts argument positions from 0, so the first argument is index 0 and the second argument is index 1.
Do this insteadRead {0} as the first argument and {1} as the second argument.
Common mistake Using plus concatenation with a non-string value without conversion
What it looks like"Age: " + ageWhy it failsConcatenation with plus requires non-string values to be explicitly converted with
str().Do this insteadUse "Age: " + str(age), or use "Age: {}".format(age).Common mistake Adding a format specification without the colon
What it looks like"{0.3f}"Why it failsThe format specification comes after a colon inside the braces.
Do this insteadWrite "{0:.3f}" when selecting argument 0 and displaying three digits after the decimal point.
Common mistake Assuming empty braces can express a reordered argument
What it looks like"{} {}".format("first", "second")Why it failsEmpty braces consume arguments in order from left to right.
Do this insteadUse 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
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
- 1
format()builds a string by replacing curly-brace placeholders with supplied argument values. - 2Numbered placeholders use zero-based positional indices: {0} refers to the first argument, {1} to the second, and so on.
- 3Empty braces insert arguments from left to right, while explicit indices support reordered or repeated values.
- 4A colon introduces a format specification, such as :.3f for decimal precision or :_^11 for centered padding.
- 5
format()automatically converts values to strings and separates the message template from the data more clearly than manual plus concatenation.
At a glance
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.