Python 3 reference · String Methods

Python String format() Method

Return a formatted string, filling {} placeholders with the arguments. f-strings are usually simpler.

Python 3 Since 3.0

Syntax

str.format(*args, **kwargs)

Parameters

ParameterDescription
*args, **kwargs Values for positional {} / {0} and named {name} placeholders.

Return value

A new string.

Examples

Positional and named fieldsTry it yourself
print("{} is {} years old".format("Ada", 36))
print("{name} likes {lang}".format(name="Ada", lang="Python"))

Output

Ada is 36 years old
Ada likes Python
Format specsTry it yourself
print("{:.2f} | {:>6} | {:,}".format(3.14159, "right", 1234567))

Output

3.14 |  right | 1,234,567
Reusable templatesTry it yourself
template = "Hello, {name}!"  # reusable template
for n in ["Ada", "Linus"]:
    print(template.format(name=n))

Output

Hello, Ada!
Hello, Linus!

Use f-strings (f"{name} is {age}") for one-off formatting and format() when the template is stored or comes from elsewhere.

Version history

VersionChange
Python 3.0Added