Python String format() Method

Short answer
str.format() fills {} placeholders in a string with the values you pass in, for example "Hi {}".format("Asha") gives 'Hi Asha'. Format specs such as {:.2f} control decimals, width and alignment.

format() builds text from a template. You write the fixed text once, mark the gaps with braces, and hand over the values. Since Python 3.6, f-strings are usually shorter for new code, but format() is still everywhere in existing programs, and it is the right tool when the template is stored separately from the data (in a config file, a translation, or a variable). It returns a new string; the original is never changed.

Quick facts
Syntaxtemplate.format(*args, **kwargs)
ParametersPositional values (for {} and {0}) and keyword values (for {name})
ReturnsA new formatted string
Literal bracesWrite {{ and }}
Format spec{field:spec}, for example {:>8}, {:,.2f}, {:05d}

Placeholders: automatic, numbered and named fields

There are three ways to point a placeholder at a value.

Python
print("{} scored {}".format("Asha", 92))
print("{1} scored {0}".format(92, "Asha"))
print("{name} scored {mark}".format(name="Asha", mark=92))

Automatic {} fields take the values in order. Numbered fields {0}, {1} can repeat and reorder values. Named fields read more clearly in long templates. Do not mix automatic and numbered fields in one template; Python raises ValueError.

Format specifiers for numbers, width and alignment

After a colon you can add a format spec. The most useful parts are an alignment (< left, > right, ^ centre), a width, a thousands separator (,) and a precision with a type (.2f).

Python
print("{:.2f}".format(3.14159))
print("{:,}".format(1234567))
print("{:>8}|{:<8}|{:^8}|".format("ab", "cd", "ef"))
print("{:05d}".format(42))
print("{:.1%}".format(0.256))

The same mini-language is used inside f-strings, so what you learn here carries over.

Common format spec codes

SpecMeaningExample callResult
.2fTwo decimals"{:.2f}".format(2.5)2.50
,Thousands separator"{:,}".format(1000000)1,000,000
05dZero-pad to width 5"{:05d}".format(7)00007
>6Right-align in 6"{:>6}".format("hi")hi
*^7Centre, fill with *"{:*^7}".format("hi")**hi***
bBinary"{:b}".format(5)101
xHexadecimal"{:x}".format(255)ff
.1%Percentage"{:.1%}".format(0.5)50.0%

format() vs f-strings vs the % operator

Prefer an f-string when the values are variables in the same place as the text. Use format() when the template is built elsewhere or reused with different data, for example template.format(**row) with a dictionary. The old % style still works but is harder to read. See the f-strings lesson and string methods for the wider picture.

Examples you can run

Press Run, then edit the code and run it again.

Insert values into a sentence

Automatic and named fields in the same program.

Insert values into a sentence
name = "Asha"
city = "Pune"
print("{} lives in {}.".format(name, city))
print("{who} lives in {where}.".format(who=name, where=city))
Expected outputAsha lives in Pune.
Asha lives in Pune.

Format money and a receipt line

Width, alignment and precision combine to line up columns.

Format money and a receipt line
items = [("Pen", 12.5, 4), ("Notebook", 80, 2)]
for name, price, qty in items:
    print("{:<10}{:>8.2f}{:>4}".format(name, price, qty))
Expected outputPen          12.50   4
Notebook     80.00   2

Fill a template from a dictionary

**row unpacks the dictionary into named fields, so the template is reusable.

Fill a template from a dictionary
template = "Dear {name}, your order {order} is {status}."
row = {"name": "Ravi", "order": "A-102", "status": "shipped"}
print(template.format(**row))
Expected outputDear Ravi, your order A-102 is shipped.

Print literal braces

Double the braces to show a real { or }.

Print literal braces
print("Set syntax: {{1, 2, 3}} has {} items".format(3))
Expected outputSet syntax: {1, 2, 3} has 3 items

Common mistakes

Not enough values for the placeholders

✗ Wrong

print("{} and {}".format("tea"))
IndexError: Replacement index 1 out of range for positional args tuple

✓ Right

print("{0} and {0}".format("tea"))

Supply one value for each {}, or use numbered fields to reuse one value.

Using a name that was not passed

✗ Wrong

print("Hello {name}".format(user="Asha"))
KeyError: 'name'

✓ Right

print("Hello {name}".format(name="Asha"))

The keyword in format() must match the name inside the braces.

Forgetting to double literal braces

✗ Wrong

print("{ready}".format())
KeyError: 'ready'

✓ Right

print("{{ready}}".format())

Use {{ and }} when you want braces in the output.

Python String format() Method: questions people ask

What does str.format() do in Python?

It replaces {} placeholders in a string with the values you pass and returns the new string. It can also format numbers, such as {:.2f}.

Should I use format() or f-strings?

Use f-strings for new code where values are in scope, and format() when the template is stored separately or reused with different data.

How do I format a float to 2 decimal places with format()?

Use "{:.2f}".format(value). For example "{:.2f}".format(3.14159) gives '3.14'.

Keep learning

Step-by-step lessons:
Python f-StringsPython StringsPython String Methods

Related:
Python String center() MethodPython String zfill() MethodHow to Convert an Int to a String in PythonPython Input and Output

More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String replace() MethodPython String upper() MethodPython String lower() Method See all →