Python Reference ยท String Methods
Python str.format() method
Reference for Python str.format(): replacement fields, positional and named arguments, attribute and index access, conversions, format specs and errors.
The str.format() method builds a new string by filling in replacement fields, the parts of the template written in curly braces, with the arguments you pass. Each field can say which argument to use, how to convert it and how to format it (width, alignment, number of decimals and so on).
Since Python 3.6 most code uses f-strings for formatting values that are already in variables, but format() remains important when the template is stored separately from the data, for example in a translation file, a config option or a constant reused with different values.
print("{} is {} years old".format("Ada", 36)) # Ada is 36 years old
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
template.format(*args, **kwargs)
A replacement field looks like {field_name!conversion:format_spec}, and all three parts are optional.
| Part | Description |
|---|---|
field_name |
Empty (next positional argument), a number (), or a name (). It may be followed by .attribute or [index] lookups. |
!conversion |
!s calls str(), !r calls repr(), !a calls ascii() before formatting. |
format_spec |
The same mini-language as format(): fill, alignment, sign, width, grouping, precision and type. Nested {} fields are allowed. |
| Name | Description |
|---|---|
*args |
Positional values, numbered from 0. |
**kwargs |
Keyword values, used by name. |
Return value: a new str.
Raises: IndexError for a missing positional argument, KeyError for a missing name, ValueError for a malformed template or a spec that does not suit the value (for example {:d} with a string), and ValueError when automatic and manual numbering are mixed.
Usage notes
- Do not mix numbering styles.
"{} {1}"fails; use all empty fields or all numbers. - Extra arguments are ignored.
"{}".format(1, 2)returns"1"with no complaint, which can hide mistakes. - Braces are escaped by doubling. Write
{{and}}for literal braces. This is a common nuisance when formatting JSON or CSS text; building the structure with thejsonmodule is safer. - Index keys are not quoted. In
{0[x]}the key is the textx. A purely numeric key is treated as an integer index, so use{0[1]}for lists and tuples. Dictionaries with integer keys are best formatted another way. - Never format untrusted templates. Attribute access lets a template reach into objects (
"{0.__class__}"), which can expose internals. Fill untrusted data into trusted templates, not the other way around. - Missing keys:
format_map()accepts a mapping directly and works with__missing__(). - Compared with f-strings. F-strings evaluate expressions in place and are shorter;
format()lets you define the template first and the data later. Both use the same specs. - Compared with
%. Old-style"%s" % valueformatting still works but has fewer features.
Related
format(),str.format_map(),str.center(),str.zfill(),repr()- Lessons: String formatting, Strings