Skip to content

Commit bc1ee46

Browse files
committed
Issue python#25179: Documentation for formatted string literals aka f-strings
Some of the inspiration and wording is taken from the text of PEP 498 by Eric V. Smith, and the existing str.format() documentation.
1 parent e0b2309 commit bc1ee46

10 files changed

Lines changed: 158 additions & 21 deletions

File tree

Doc/faq/programming.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,8 @@ How do I convert a number to a string?
839839
To convert, e.g., the number 144 to the string '144', use the built-in type
840840
constructor :func:`str`. If you want a hexadecimal or octal representation, use
841841
the built-in functions :func:`hex` or :func:`oct`. For fancy formatting, see
842-
the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
842+
the :ref:`f-strings` and :ref:`formatstrings` sections,
843+
e.g. ``"{:04d}".format(144)`` yields
843844
``'0144'`` and ``"{:.3f}".format(1.0/3.0)`` yields ``'0.333'``.
844845

845846

Doc/library/datetime.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,8 @@ Instance methods:
605605
.. method:: date.__format__(format)
606606

607607
Same as :meth:`.date.strftime`. This makes it possible to specify a format
608-
string for a :class:`.date` object when using :meth:`str.format`. For a
608+
string for a :class:`.date` object in :ref:`formatted string
609+
literals <f-strings>` and when using :meth:`str.format`. For a
609610
complete list of formatting directives, see
610611
:ref:`strftime-strptime-behavior`.
611612

@@ -1180,7 +1181,8 @@ Instance methods:
11801181
.. method:: datetime.__format__(format)
11811182

11821183
Same as :meth:`.datetime.strftime`. This makes it possible to specify a format
1183-
string for a :class:`.datetime` object when using :meth:`str.format`. For a
1184+
string for a :class:`.datetime` object in :ref:`formatted string
1185+
literals <f-strings>` and when using :meth:`str.format`. For a
11841186
complete list of formatting directives, see
11851187
:ref:`strftime-strptime-behavior`.
11861188

@@ -1425,7 +1427,8 @@ Instance methods:
14251427
.. method:: time.__format__(format)
14261428

14271429
Same as :meth:`.time.strftime`. This makes it possible to specify a format string
1428-
for a :class:`.time` object when using :meth:`str.format`. For a
1430+
for a :class:`.time` object in :ref:`formatted string
1431+
literals <f-strings>` and when using :meth:`str.format`. For a
14291432
complete list of formatting directives, see
14301433
:ref:`strftime-strptime-behavior`.
14311434

Doc/library/enum.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,8 @@ Some rules:
558558
4. %-style formatting: `%s` and `%r` call the :class:`Enum` class's
559559
:meth:`__str__` and :meth:`__repr__` respectively; other codes (such as
560560
`%i` or `%h` for IntEnum) treat the enum member as its mixed-in type.
561-
5. :meth:`str.format` (or :func:`format`) will use the mixed-in
561+
5. :ref:`Formatted string literals <f-strings>`, :meth:`str.format`,
562+
and :func:`format` will use the mixed-in
562563
type's :meth:`__format__`. If the :class:`Enum` class's :func:`str` or
563564
:func:`repr` is desired, use the `!s` or `!r` format codes.
564565

Doc/library/stdtypes.rst

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,8 +1450,8 @@ multiple fragments.
14501450

14511451
For more information on the ``str`` class and its methods, see
14521452
:ref:`textseq` and the :ref:`string-methods` section below. To output
1453-
formatted strings, see the :ref:`formatstrings` section. In addition,
1454-
see the :ref:`stringservices` section.
1453+
formatted strings, see the :ref:`f-strings` and :ref:`formatstrings`
1454+
sections. In addition, see the :ref:`stringservices` section.
14551455

14561456

14571457
.. index::
@@ -2053,8 +2053,8 @@ expression support in the :mod:`re` module).
20532053
.. index::
20542054
single: formatting, string (%)
20552055
single: interpolation, string (%)
2056-
single: string; formatting
2057-
single: string; interpolation
2056+
single: string; formatting, printf
2057+
single: string; interpolation, printf
20582058
single: printf-style formatting
20592059
single: sprintf-style formatting
20602060
single: % formatting
@@ -2064,9 +2064,10 @@ expression support in the :mod:`re` module).
20642064

20652065
The formatting operations described here exhibit a variety of quirks that
20662066
lead to a number of common errors (such as failing to display tuples and
2067-
dictionaries correctly). Using the newer :meth:`str.format` interface
2068-
helps avoid these errors, and also provides a generally more powerful,
2069-
flexible and extensible approach to formatting text.
2067+
dictionaries correctly). Using the newer :ref:`formatted
2068+
string literals <f-strings>` or the :meth:`str.format` interface
2069+
helps avoid these errors. These alternatives also provide more powerful,
2070+
flexible and extensible approaches to formatting text.
20702071

20712072
String objects have one unique built-in operation: the ``%`` operator (modulo).
20722073
This is also known as the string *formatting* or *interpolation* operator.

Doc/library/string.rst

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,9 @@ Format String Syntax
188188

189189
The :meth:`str.format` method and the :class:`Formatter` class share the same
190190
syntax for format strings (although in the case of :class:`Formatter`,
191-
subclasses can define their own format string syntax).
191+
subclasses can define their own format string syntax). The syntax is
192+
related to that of :ref:`formatted string literals <f-strings>`, but
193+
there are differences.
192194

193195
Format strings contain "replacement fields" surrounded by curly braces ``{}``.
194196
Anything that is not contained in braces is considered literal text, which is
@@ -283,7 +285,8 @@ Format Specification Mini-Language
283285

284286
"Format specifications" are used within replacement fields contained within a
285287
format string to define how individual values are presented (see
286-
:ref:`formatstrings`). They can also be passed directly to the built-in
288+
:ref:`formatstrings` and :ref:`f-strings`).
289+
They can also be passed directly to the built-in
287290
:func:`format` function. Each formattable type may define how the format
288291
specification is to be interpreted.
289292

@@ -308,7 +311,8 @@ The general form of a *standard format specifier* is:
308311
If a valid *align* value is specified, it can be preceded by a *fill*
309312
character that can be any character and defaults to a space if omitted.
310313
It is not possible to use a literal curly brace ("``{``" or "``}``") as
311-
the *fill* character when using the :meth:`str.format`
314+
the *fill* character in a :ref:`formatted string literal
315+
<f-strings>` or when using the :meth:`str.format`
312316
method. However, it is possible to insert a curly brace
313317
with a nested replacement field. This limitation doesn't
314318
affect the :func:`format` function.

Doc/reference/datamodel.rst

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1234,8 +1234,9 @@ Basic customization
12341234

12351235
.. method:: object.__format__(self, format_spec)
12361236

1237-
Called by the :func:`format` built-in function (and by extension, the
1238-
:meth:`str.format` method of class :class:`str`) to produce a "formatted"
1237+
Called by the :func:`format` built-in function,
1238+
and by extension, evaluation of :ref:`formatted string literals
1239+
<f-strings>` and the :meth:`str.format` method, to produce a "formatted"
12391240
string representation of an object. The ``format_spec`` argument is
12401241
a string that contains a description of the formatting options desired.
12411242
The interpretation of the ``format_spec`` argument is up to the type

Doc/reference/lexical_analysis.rst

Lines changed: 106 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,8 @@ String literals are described by the following lexical definitions:
405405

406406
.. productionlist::
407407
stringliteral: [`stringprefix`](`shortstring` | `longstring`)
408-
stringprefix: "r" | "u" | "R" | "U"
408+
stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
409+
: | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
409410
shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
410411
longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
411412
shortstringitem: `shortstringchar` | `stringescapeseq`
@@ -464,6 +465,11 @@ is not supported.
464465
to simplify the maintenance of dual Python 2.x and 3.x codebases.
465466
See :pep:`414` for more information.
466467

468+
A string literal with ``'f'`` or ``'F'`` in its prefix is a
469+
:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be
470+
combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw
471+
formatted strings are possible, but formatted bytes literals are not.
472+
467473
In triple-quoted literals, unescaped newlines and quotes are allowed (and are
468474
retained), except that three unescaped quotes in a row terminate the literal. (A
469475
"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.)
@@ -584,7 +590,105 @@ comments to parts of strings, for example::
584590
Note that this feature is defined at the syntactical level, but implemented at
585591
compile time. The '+' operator must be used to concatenate string expressions
586592
at run time. Also note that literal concatenation can use different quoting
587-
styles for each component (even mixing raw strings and triple quoted strings).
593+
styles for each component (even mixing raw strings and triple quoted strings),
594+
and formatted string literals may be concatenated with plain string literals.
595+
596+
597+
.. index::
598+
single: formatted string literal
599+
single: interpolated string literal
600+
single: string; formatted literal
601+
single: string; interpolated literal
602+
single: f-string
603+
.. _f-strings:
604+
605+
Formatted string literals
606+
-------------------------
607+
608+
.. versionadded:: 3.6
609+
610+
A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
611+
that is prefixed with ``'f'`` or ``'F'``. These strings may contain
612+
replacement fields, which are expressions delimited by curly braces ``{}``.
613+
While other string literals always have a constant value, formatted strings
614+
are really expressions evaluated at run time.
615+
616+
Escape sequences are decoded like in ordinary string literals (except when
617+
a literal is also marked as a raw string). After decoding, the grammar
618+
for the contents of the string is:
619+
620+
.. productionlist::
621+
f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
622+
replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}"
623+
f_expression: `conditional_expression` ("," `conditional_expression`)* [","]
624+
: | `yield_expression`
625+
conversion: "s" | "r" | "a"
626+
format_spec: (`literal_char` | NULL | `replacement_field`)*
627+
literal_char: <any code point except "{", "}" or NULL>
628+
629+
The parts of the string outside curly braces are treated literally,
630+
except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
631+
with the corresponding single curly brace. A single opening curly
632+
bracket ``'{'`` marks a replacement field, which starts with a
633+
Python expression. After the expression, there may be a conversion field,
634+
introduced by an exclamation point ``'!'``. A format specifier may also
635+
be appended, introduced by a colon ``':'``. A replacement field ends
636+
with a closing curly bracket ``'}'``.
637+
638+
Expressions in formatted string literals are treated like regular
639+
Python expressions surrounded by parentheses, with a few exceptions.
640+
An empty expression is not allowed, and a :keyword:`lambda` expression
641+
must be surrounded by explicit parentheses. Replacement expressions
642+
can contain line breaks (e.g. in triple-quoted strings), but they
643+
cannot contain comments. Each expression is evaluated in the context
644+
where the formatted string literal appears, in order from left to right.
645+
646+
If a conversion is specified, the result of evaluating the expression
647+
is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
648+
the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
649+
650+
The result is then formatted using the :func:`format` protocol. The
651+
format specifier is passed to the :meth:`__format__` method of the
652+
expression or conversion result. An empty string is passed when the
653+
format specifier is omitted. The formatted result is then included in
654+
the final value of the whole string.
655+
656+
Top-level format specifiers may include nested replacement fields.
657+
These nested fields may include their own conversion fields and
658+
format specifiers, but may not include more deeply-nested replacement fields.
659+
660+
Formatted string literals may be concatenated, but replacement fields
661+
cannot be split across literals.
662+
663+
Some examples of formatted string literals::
664+
665+
>>> name = "Fred"
666+
>>> f"He said his name is {name!r}."
667+
"He said his name is 'Fred'."
668+
>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
669+
"He said his name is 'Fred'."
670+
>>> width = 10
671+
>>> precision = 4
672+
>>> value = decimal.Decimal("12.34567")
673+
>>> f"result: {value:{width}.{precision}}" # nested fields
674+
'result: 12.35'
675+
676+
A consequence of sharing the same syntax as regular string literals is
677+
that characters in the replacement fields must not conflict with the
678+
quoting used in the outer formatted string literal. Also, escape
679+
sequences normally apply to the outer formatted string literal,
680+
rather than inner string literals::
681+
682+
f"abc {a["x"]} def" # error: outer string literal ended prematurely
683+
f"abc {a[\"x\"]} def" # workaround: escape the inner quotes
684+
f"abc {a['x']} def" # workaround: use different quoting
685+
686+
f"newline: {ord('\n')}" # error: literal line break in inner string
687+
f"newline: {ord('\\n')}" # workaround: double escaping
688+
fr"newline: {ord('\n')}" # workaround: raw outer string
689+
690+
See also :pep:`498` for the proposal that added formatted string literals,
691+
and :meth:`str.format`, which uses a related format string mechanism.
588692

589693

590694
.. _numbers:

Doc/tutorial/inputoutput.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ first way is to do all the string handling yourself; using string slicing and
2525
concatenation operations you can create any layout you can imagine. The
2626
string type has some methods that perform useful operations for padding
2727
strings to a given column width; these will be discussed shortly. The second
28-
way is to use the :meth:`str.format` method.
28+
way is to use :ref:`formatted string literals <f-strings>`, or the
29+
:meth:`str.format` method.
2930

3031
The :mod:`string` module contains a :class:`~string.Template` class which offers
3132
yet another way to substitute values into strings.

Doc/tutorial/introduction.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,9 @@ The built-in function :func:`len` returns the length of a string::
352352
Strings support a large number of methods for
353353
basic transformations and searching.
354354

355+
:ref:`f-strings`
356+
String literals that have embedded expressions.
357+
355358
:ref:`formatstrings`
356359
Information about string formatting with :meth:`str.format`.
357360

Doc/whatsnew/3.6.rst

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ Summary -- Release highlights
6262
.. This section singles out the most important changes in Python 3.6.
6363
Brevity is key.
6464
65-
* None yet.
65+
* PEP 498: :ref:`Formatted string literals <whatsnew-fstrings>`
6666

6767
.. PEP-sized items next.
6868
@@ -80,6 +80,24 @@ Summary -- Release highlights
8080
PEP written by Carl Meyer
8181

8282

83+
.. _whatsnew-fstrings:
84+
85+
PEP 498: Formatted string literals
86+
----------------------------------
87+
88+
Formatted string literals are a new kind of string literal, prefixed
89+
with ``'f'``. They are similar to the format strings accepted by
90+
:meth:`str.format`. They contain replacement fields surrounded by
91+
curly braces. The replacement fields are expressions, which are
92+
evaluated at run time, and then formatted using the :func:`format` protocol.
93+
94+
>>> name = "Fred"
95+
>>> f"He said his name is {name}."
96+
'He said his name is Fred.'
97+
98+
See :pep:`498` and the main documentation at :ref:`f-strings`.
99+
100+
83101
Other Language Changes
84102
======================
85103

0 commit comments

Comments
 (0)