Concepts / String Concatenation

String Concatenation

The format() method constructs strings by substituting placeholders with argument values, replacing the need for error-prone string concatenation.

  • Programming

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

{0}{1}substitutessubstitutesHello, {0}! You are{1}.templatenameSwaroopage20Hello, Swaroop! Youare 20.result
What happens to a template string and its placeholders as format() replaces them with actual values?

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

uses argument 0uses argument 1{0}first positionnameSwaroop{1}second positionage20
How does each numbered placeholder such as {0} or {1} connect to the corresponding argument passed to format()?

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.

python
Output
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.

python

Controlling Display Details

{start0argument index:begins specification.3fthree decimal places}end
How do format specifications control decimal precision, alignment, and padding in the resulting string?

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

SpecificationMeaningSource example
{0:.3f}Use argument 0 as a float and show 3 digits after the decimal point1.0 / 3 becomes 0.333
{0:_^11}Center argument 0 in a width of 11 and use underscores as paddinghello becomes ___hello___

Two format specifications described in the source examples

python

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

requires for non-string valuesprovidesPlus concatenationpieces joined manuallystr(age)explicit conversionformat() templatemessage and data separatedautomatic conversionformat() converts values
What is the difference between assembling a message with plus concatenation and assembling it with a format() template?
AspectPlus concatenationformat()
Message constructionJoins separate pieces manuallyUses a template with placeholders
Non-string valuesRequires explicit str() callsAutomatically converts values to strings
ReadabilityCan become visually clutteredKeeps the message shape clear
Changing the messageMay require editing several joined piecesThe template can be changed separately from the variables
python

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

  • 20 is Swaroop years old.
  • Swaroop is 20 years old.
  • The placeholders are filled from left to right without using the indices.
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().

EASY

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

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.
  2. Numbered placeholders use zero-based positional indices: {0} refers to the first argument, {1} to the second, and so on.
  3. Empty braces insert arguments from left to right, while explicit indices support reordered or repeated values.
  4. A 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.

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.