In Python, format() builds a new string by filling {} placeholders with values you pass.
You can use positional fields, named fields, or both. Format specifiers after a colon control width, precision, and alignment.
Syntax
Call format on a template string. Start with this line.
python
msg = "Hello, {}!".format(name)
Call
What it does
"{} {}".format("Ada", "Lovelace")
Fills positional fields.
"{name}".format(name="Ada")
Fills a named field.
For one-off text, f-strings are often clearer. Keep format() for reusable templates.
Library declarations
python
str.format(*args, **kwargs) → str
Parameters
Parameter
Description
*args
Optional. Positional values for {} or {0}, {1}.
**kwargs
Optional. Named values for {name} placeholders.
Return Value
Return Value
Description
str
A new string with placeholders replaced.
Python Examples
Example 1 — Positional Placeholders
Empty {} slots fill left to right from the arguments.
python
msg = "{}, {} and {}".format("red", "green", "blue")
print(msg)
# reuse / reorder with indexes
print("{1} then {0}".format("first", "second"))
Output
red, green and blue
second then first
How It Works
Three empty braces. They take args 0, 1, and 2 in order.
Result joins cleanly. Output is one readable sentence.
Numbered fields.{1} and {0} pick arguments by index.
Reorder without rewriting data. Handy for templates that share values.
Example 2 — Named Placeholders
Keyword arguments make templates easier to read and maintain.
python
template = "{user} has {points} points"
print(template.format(user="Ada", points=120))
# names can appear more than once
print("{x} + {x} = {y}".format(x=2, y=4))
Output
Ada has 120 points
2 + 2 = 4
How It Works
Name each slot.{user} and {points} match keywords.
Pass keywords in any order. Matching is by name, not position.
Reuse a name.{x} appears twice with the same value.
Clearer templates. Often better than many bare {} slots.
Example 3 — Format Specifiers
Control precision, alignment, and separators after the colon.
python
price = 1234.5
print("{:.2f}".format(price))
print("{:>10}".format("hi"))
print("{:,}".format(1000000))
# same ideas with an f-string:
# f"{price:.2f}"
Output
1234.50
hi
1,000,000
How It Works
.2f. Forces two decimal places (adds a trailing 0).
>10. Right-aligns in a field 10 characters wide.
,. Inserts a thousands separator.
Same mini-language. Specifiers also work inside f-strings.
Frequently Asked Questions
It replaces placeholders in a template with the values you provide.
A new str. The template is not modified.
f-strings embed values in the literal. format() keeps the template separate.
Use a specifier after a colon, such as {:.2f} or {:,}.
format_map(mapping) fills named placeholders from a mapping object.