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.
Fundamentals
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.
Foundation
📝 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 "}}".
Cheat Sheet
⚡ Quick Reference
Expression
Result
"{} + {} = {}".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
Hands-On
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)
📤 Output:
Template: My name is {} and I am {} years old.
Result: My name is Alice and I am 30 years old.
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)
📤 Output:
I have banana and apple.
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)
📤 Output:
The orange is delicious.
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.
The price is $19.96.
Tax rate: 7.5%
Large total: 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)
📤 Output:
format(): Hello, my name is Bob and I'm 25 years old.
f-string: Hello, my name is Bob and I'm 25 years old.
Equal? True
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().
Reference
↩ 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:
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.
Important
📝 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about format()
Use these points when building formatted strings in Python.
5
Core concepts
📝01
Returns str
New string, not None.
Return
🔗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.