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
| Parameter | Description |
|---|---|
*args, **kwargs |
Values for positional {} / {0} and named {name} placeholders. |
Return value
A new string.
Examples
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
print("{:.2f} | {:>6} | {:,}".format(3.14159, "right", 1234567))
Output
3.14 | right | 1,234,567
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.format_map()· Like format(), but takes the values from a single mapping, which can be a dict or a dict subclass with defaults.str.center()· Return the string centred in a field of the given width, padded on both sides with a fill character (a space by default).- Python String Formatting · tutorial