Python format() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The format() method builds dynamic strings by filling {} placeholders with values you pass in. It supports positional arguments, numbered indices, named keywords, and powerful format specifiers for numbers and alignment. It is one of Python’s core string-formatting tools—and the foundation behind reusable templates and format_map().

01

{} Placeholders

Insert values in order.

02

{0} {1} Index

Reorder arguments.

03

{name} Keys

Named placeholders.

04

Format Specs

:.2f, :>10, :,

05

New String

Returns formatted str.

06

vs f-strings

Templates vs inline.

Definition and Usage

In Python, format() is called on a template string that contains replacement fields inside curly braces. You pass values as positional arguments, keyword arguments, or both. Python substitutes each field and returns a brand-new string.

For example, "Hello, {}!".format("World") produces "Hello, World!". Named fields like {name} are filled with keyword arguments: "Hello, {name}!".format(name="Alice").

💡
Beginner Tip

Always assign the result: result = template.format(...). The template string itself never changes—strings in Python are immutable.

📝 Syntax

The format() method accepts positional and keyword arguments:

python
string.format(*args, **kwargs)

Syntax Rules

  • {} — auto-numbered positional placeholders (filled in order).
  • {0}, {1} — explicit index; reuse an index to repeat a value.
  • {name} — named placeholder; pass name=value as a keyword argument.
  • {value:spec} — format specifier after colon (width, precision, alignment).
  • Return value — a new str; the original template is unchanged.
  • Literal braces — escape with doubling: "{{" and "}}".

⚡ Quick Reference

ExpressionResult
"{} + {} = {}".format(2, 3, 5)"2 + 3 = 5"
"{1} and {0}".format("apple", "banana")"banana and apple"
"Hi, {name}!".format(name="Ada")"Hi, Ada!"
"${:.2f}".format(19.956)"$19.96"
"{{literal}}".format()"{literal}"
Basic
"{}".format(value)

Positional fill

Named
"{k}".format(k=v)

Keyword args

Number
"{:.2f}".format(n)

Two decimals

Align
"{:>10}".format(s)

Right-align width

Examples Gallery

Run these examples in any Python 3 interpreter. Each demonstrates a different way to use placeholders and format specifiers.

📚 Getting Started

Replace empty {} fields with values in order.

Example 1 — Basic format()

Fill two placeholders with a name and age.

python
name = "Alice"
age = 30
template = "My name is {} and I am {} years old."

result = template.format(name, age)

print("Template:", template)
print("Result:  ", result)

How It Works

  • The first {} receives name; the second receives age.
  • format() returns a new string—the template still contains {}.
  • You can pass any objects; Python converts them to strings automatically.

Example 2 — Placeholder Indexing

Use {0} and {1} to control argument order.

python
item1 = "apple"
item2 = "banana"

sentence = "I have {1} and {0}.".format(item1, item2)
print(sentence)

How It Works

{1} refers to the second argument (item2) and {0} to the first (item1). You can reuse an index—{0} twice prints the same value twice without passing it again.

📈 Practical Patterns

Named fields, numeric precision, and modern alternatives.

Example 3 — Named Placeholders

Keyword arguments make templates self-documenting.

python
sentence = "The {fruit} is {adjective}.".format(
    fruit="orange",
    adjective="delicious"
)
print(sentence)

How It Works

Each {name} in the template must match a keyword argument. Order no longer matters—ideal for templates with many fields or translated strings.

Example 4 — Formatting Numbers

Control decimal places with a format specifier.

python
price = 19.956
tax_rate = 0.075

print("The price is ${:.2f}.".format(price))
print("Tax rate:     {:.1%}".format(tax_rate))
print("Large total:  {:,}".format(1_250_000))

How It Works

  • {:.2f} rounds to two decimal places as a float.
  • {:.1%} multiplies by 100 and adds a percent sign.
  • {:,} inserts thousands separators for readability.

Example 5 — format() vs f-strings

Both produce the same result; choose based on whether the template is separate.

python
name = "Bob"
age = 25

via_format = "Hello, my name is {} and I'm {} years old.".format(name, age)
via_fstring = f"Hello, my name is {name} and I'm {age} years old."

print("format():", via_format)
print("f-string:", via_fstring)
print("Equal?   ", via_format == via_fstring)

How It Works

f-strings (Python 3.6+) embed variables directly and are great for quick messages. format() shines when the template is stored in a variable, loaded from a file, or reused with different data via format_map().

↩ Return Value

format() returns a new string with all placeholders replaced. It does not modify the original template, and it does not return None. Because strings are immutable, you must capture the result:

python
template = "Hello, {}!"
result = template.format("World")

print(result)      # Hello, World!
print(template)    # Hello, {}!  (unchanged)

🚀 Common Use Cases

  • User messages — personalize greetings, confirmations, and error text.
  • Reports and invoices — align columns and format currency with specifiers.
  • Internationalization — store translated templates and fill them at runtime.
  • Logging — build structured log lines from reusable format strings.
  • Config templates — keep patterns in JSON/YAML and apply values with format() or format_map().

🧠 How format() Works

1

Python parses placeholder fields

Each {}, {0}, or {name:spec} field in the template is identified.

Parse
2

Arguments are matched to fields

Positional args fill auto-numbered or indexed fields; keyword args fill named fields.

Match
3

Values are formatted and substituted

Format specifiers control width, precision, and type conversion before insertion.

Format
=

New string returned

The completed string is returned; the original template remains unchanged.

📝 Notes

  • format() is more flexible and readable than the older % operator ("%s" % name).
  • f-strings (Python 3.6+) are often the shortest choice for inline formatting; format() remains essential for stored templates.
  • Mixing auto-numbered {} with explicit {0} in the same string raises ValueError.
  • Every placeholder must receive a value—missing arguments raise IndexError or KeyError.
  • For dictionary-only data, format_map(data) or format(**data) avoids repeating keyword names.

Conclusion

The format() method is Python’s flexible answer to dynamic string building. From simple {} substitution to precise numeric formatting, it covers most everyday templating needs.

Remember that it always returns a new string—never None. Use named placeholders for clarity, format specifiers for numbers, and reach for f-strings when the whole message lives in one literal. For dictionary-driven templates, explore format_map() next.

💡 Best Practices

✅ Do

  • Assign the return value: msg = tpl.format(...)
  • Use named placeholders in templates with many fields
  • Apply format specifiers for currency, dates, and aligned columns
  • Store reusable templates as constants or config values
  • Prefer f-strings for short, one-off messages in Python 3.6+

❌ Don’t

  • Assume format() changes the template in place—it does not
  • Ignore the return value and expect the template to update
  • Mix {} and {0} in the same format string
  • Use format() to build SQL or shell commands from user input
  • Rely on % formatting in new Python 3 code without good reason

Key Takeaways

Knowledge Unlocked

Five things to remember about format()

Use these points when building formatted strings in Python.

5
Core concepts
🔗 02

{} and {name}

Positional or named.

Syntax
📈 03

Format Specs

:.2f, :>10, :,

Power
🛠 04

Templates

Reuse stored strings.

Use case
05

vs f-strings

Inline vs template.

Compare

❓ Frequently Asked Questions

format() replaces placeholders in a string with values you provide. Placeholders use curly braces like {} or {name}. It returns a new formatted string and does not change the original.
string.format(*args, **kwargs). Positional values fill {} or {0}, {1}; keyword arguments fill {name} placeholders. You can mix both in one call.
It returns a new str with placeholders replaced. It does not return None and does not modify the original string, because Python strings are immutable.
f-strings embed variables directly in the literal: f"Hello, {name}". format() keeps the template separate: "Hello, {}".format(name). f-strings are often shorter; format() is better for reusable templates.
Use a format specifier inside the braces, such as {:.2f} for two decimal places, {:,} for thousands separators, or {:>10} for right-aligned width.
Yes for most modern code. The older % operator (%s, %d) still works but format() and f-strings are clearer, more flexible, and the recommended approach in Python 3.

Explore More Python String Methods

Continue with format_map(), index(), and the rest of the string method reference.

Next: format_map() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful