Skip to content

Commit 0d8a917

Browse files
committed
Work on f-strings
1 parent d593940 commit 0d8a917

File tree

2 files changed

+101
-180
lines changed

2 files changed

+101
-180
lines changed

Doc/library/stdtypes.rst

Lines changed: 62 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -2536,123 +2536,98 @@ Formatted String Literals (f-strings)
25362536
The :keyword:`await` and :keyword:`async for` can be used in expressions
25372537
within f-strings.
25382538
.. versionchanged:: 3.8
2539-
Added the debugging operator (``=``)
2539+
Added the debug specifier (``=``)
25402540
.. versionchanged:: 3.12
25412541
Many restrictions on expressions within f-strings have been removed.
25422542
Notably, nested strings, comments, and backslashes are now permitted.
25432543

25442544
An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
25452545
a string literal that is prefixed with ``f`` or ``F``.
2546-
This type of string literal allows embedding arbitrary Python expressions
2547-
within *replacement fields*, which are delimited by curly brackets (``{}``).
2548-
These expressions are evaluated at runtime, similarly to :meth:`str.format`,
2549-
and are converted into regular :class:`str` objects.
2550-
For example:
2551-
2552-
.. doctest::
2553-
2554-
>>> who = 'nobody'
2555-
>>> nationality = 'Spanish'
2556-
>>> f'{who.title()} expects the {nationality} Inquisition!'
2557-
'Nobody expects the Spanish Inquisition!'
2558-
2559-
It is also possible to use a multi line f-string:
2560-
2561-
.. doctest::
2562-
2563-
>>> f'''This is a string
2564-
... on two lines'''
2565-
'This is a string\non two lines'
2546+
This type of string literal allows embedding the results of arbitrary Python
2547+
expressions within *replacement fields*, which are delimited by curly
2548+
brackets (``{}``).
2549+
Each replacement field must contain an expression, optionally followed by:
25662550

2567-
A single opening curly bracket, ``'{'``, marks a *replacement field* that
2568-
can contain any Python expression:
2551+
* a *debug specifier* -- an equal sign (``=``);
2552+
* a *conversion specifier* -- ``!s``, ``!r`` or ``!a``; and/or
2553+
* a *format specifier* prefixed with a colon (``:``).
25692554

2570-
.. doctest::
2555+
See the :ref:`Lexical Analysis section on f-strings <f-strings>` for details
2556+
on the syntax of these fields.
25712557

2572-
>>> nationality = 'Spanish'
2573-
>>> f'The {nationality} Inquisition!'
2574-
'The Spanish Inquisition!'
2558+
Debug specifier
2559+
^^^^^^^^^^^^^^^
25752560

2576-
To include a literal ``{`` or ``}``, use a double bracket:
2561+
.. versionadded:: 3.8
25772562

2578-
.. doctest::
2563+
If a debug specifier -- an equal sign (``=``) -- appears after the replacement
2564+
field expression, the resulting f-string will contain the expression's source,
2565+
the equal sign, and the value of the expression.
2566+
This is often useful for debugging::
25792567

2580-
>>> x = 42
2581-
>>> f'{{x}} is {x}'
2582-
'{x} is 42'
2568+
>>> print(f'{name=}')
2569+
name='Galahad'
25832570

2584-
Functions can also be used, and :ref:`format specifiers <formatstrings>`:
2571+
Whitespace on both sides of the equal sign is significant --- it is retained
2572+
in the result::
25852573

2586-
.. doctest::
2574+
>>> print(f'{name = }')
2575+
name = 'Galahad'
25872576

2588-
>>> from math import sqrt
2589-
>>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
2590-
'√2 ≈ 1.41421'
25912577

2592-
Any non-string expression is converted using :func:`str`, by default:
2578+
Conversion specifier
2579+
^^^^^^^^^^^^^^^^^^^^
25932580

2594-
.. doctest::
2581+
By default, the value of a replacement field expression is converted to
2582+
string using :func:`str`::
25952583

25962584
>>> from fractions import Fraction
2597-
>>> f'{Fraction(1, 3)}'
2585+
>>> one_third = Fraction(1, 3)
2586+
>>> f'{one_third}'
25982587
'1/3'
25992588

2600-
To use an explicit conversion, use the ``!`` (exclamation mark) operator,
2601-
followed by any of the valid formats, which are:
2589+
When a debug specifier but no format specifier is used, the default conversion
2590+
instead uses :func:`repr`::
26022591

2603-
========== ==============
2604-
Conversion Meaning
2605-
========== ==============
2606-
``!a`` :func:`ascii`
2607-
``!r`` :func:`repr`
2608-
``!s`` :func:`str`
2609-
========== ==============
2592+
>>> f'{one_third = }'
2593+
'one_third = Fraction(1, 3)'
26102594

2611-
For example:
2595+
The conversion can be specified explicitly using one of these specifiers:
26122596

2613-
.. doctest::
2597+
* ``!s`` for :func:`str`
2598+
* ``!r`` for :func:`repr`
2599+
* ``!a`` for :func:`ascii`
26142600

2615-
>>> from fractions import Fraction
2616-
>>> f'{Fraction(1, 3)!s}'
2617-
'1/3'
2618-
>>> f'{Fraction(1, 3)!r}'
2619-
'Fraction(1, 3)'
2620-
>>> question = '¿Dónde está el Presidente?'
2621-
>>> print(f'{question!a}')
2622-
'\xbfD\xf3nde est\xe1 el Presidente?'
2623-
2624-
While debugging it may be helpful to see both the expression and its value,
2625-
by using the equals sign (``=``) after the expression.
2626-
This preserves spaces within the brackets, and can be used with a converter.
2627-
By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
2628-
For example:
2601+
For example::
26292602

2630-
.. doctest::
2603+
>>> f'{one_third!r} is {one_third!s}'
2604+
'Fraction(1, 3) is 1/3'
26312605

2632-
>>> from fractions import Fraction
2633-
>>> calculation = Fraction(1, 3)
2634-
>>> f'{calculation=}'
2635-
'calculation=Fraction(1, 3)'
2636-
>>> f'{calculation = }'
2637-
'calculation = Fraction(1, 3)'
2638-
>>> f'{calculation = !s}'
2639-
'calculation = 1/3'
2640-
2641-
Once the output has been evaluated, it can be formatted using a
2642-
:ref:`format specifier <formatstrings>` following a colon (``':'``).
2643-
After the expression has been evaluated, and possibly converted to a string,
2644-
the :meth:`!__format__` method of the result is called with the format specifier,
2645-
or the empty string if no format specifier is given.
2646-
The formatted result is then used as the final value for the replacement field.
2647-
For example:
2606+
>>> string = "¡kočka 😸!"
2607+
>>> f'{string = !a}'
2608+
"string = '\\xa1ko\\u010dka \\U0001f638!'"
26482609

2649-
.. doctest::
2610+
2611+
Format specifier
2612+
^^^^^^^^^^^^^^^^
2613+
2614+
After the expression has been evaluated, and possibly converted using an
2615+
explicit conversion specifier, it is formatted using the :func:`format` function.
2616+
If the replacement field includes a *format specifier* introduced by a colon
2617+
(``:``), the specifier is passed to :func:`!format` as the second argument.
2618+
The result of :func:`!format` is then used as the final value for the
2619+
replacement field. For example::
26502620

26512621
>>> from fractions import Fraction
2652-
>>> f'{Fraction(1, 7):.6f}'
2653-
'0.142857'
2654-
>>> f'{Fraction(1, 7):_^+10}'
2655-
'___+1/7___'
2622+
>>> one_third = Fraction(1, 3)
2623+
>>> f'{one_third:.6f}'
2624+
'0.333333'
2625+
>>> f'{one_third:_^+10}'
2626+
'___+1/3___'
2627+
>>> >>> f'{one_third!r:_^20}'
2628+
'___Fraction(1, 3)___'
2629+
>>> f'{one_third = :~>10}~'
2630+
'one_third = ~~~~~~~1/3~'
26562631

26572632

26582633
.. _old-string-formatting:

Doc/reference/lexical_analysis.rst

Lines changed: 39 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -927,6 +927,14 @@ f-strings
927927
---------
928928

929929
.. versionadded:: 3.6
930+
.. versionchanged:: 3.7
931+
The :keyword:`await` and :keyword:`async for` can be used in expressions
932+
within f-strings.
933+
.. versionchanged:: 3.8
934+
Added the debug specifier (``=``)
935+
.. versionchanged:: 3.12
936+
Many restrictions on expressions within f-strings have been removed.
937+
Notably, nested strings, comments, and backslashes are now permitted.
930938

931939
A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
932940
that is prefixed with ``'f'`` or ``'F'``.
@@ -989,80 +997,49 @@ different line:
989997
990998
After the expression, replacement fields may optionally contain:
991999

992-
* a *debug specifier* -- an equal sign (``=``);
1000+
* a *debug specifier* -- an equal sign (``=``), optionally surrounded by
1001+
whitespace on one or both sides;
9931002
* a *conversion specifier* -- ``!s``, ``!r`` or ``!a``; and/or
9941003
* a *format specifier* prefixed with a colon (``:``).
9951004

996-
Debug specifier
997-
^^^^^^^^^^^^^^^
998-
999-
If a debug specifier -- an equal sign (``=``) -- appears after the replacement
1000-
field expression, the resulting f-string will contain the expression's source,
1001-
the equal sign, and the value of the expression.
1002-
This is often useful for debugging::
1003-
1004-
>>> print(f'{name=}')
1005-
name='Galahad'
1006-
1007-
Whitespace on both sides of the equal sign is significant --- it is retained
1008-
in the result::
1009-
1010-
>>> print(f'{name = }')
1011-
name = 'Galahad'
1005+
See the :ref:`Standard Library section on f-strings <stdtypes-fstrings>`
1006+
for details on how these fields are evaluated.
10121007

1008+
As that section explains, *format specifiers* are passed as the second argument
1009+
to the :func:`format` function to format a replacement field value.
1010+
For example, they can be used to specify a field width and padding characters
1011+
using the :ref:`Format Specification Mini-Language <formatspec>`::
10131012

1014-
Conversion specifier
1015-
^^^^^^^^^^^^^^^^^^^^
1013+
>>> color = 'blue'
1014+
>>> f'{color:-^20s}'
1015+
'--------blue--------'
10161016

1017-
By default, the value of a replacement field expression is converted to
1018-
string using :func:`str`::
1017+
Top-level format specifiers may include nested replacement fields::
10191018

1020-
>>> from fractions import Fraction
1021-
>>> one_third = Fraction(1, 3)
1022-
>>> f'{one_third}'
1023-
'1/3'
1024-
1025-
When a debug specifier but no format specifier is used, the default conversion
1026-
instead uses :func:`repr`::
1027-
1028-
>>> f'{one_third = }'
1029-
'one_third = Fraction(1, 3)'
1030-
1031-
The conversion can be specified explicitly using one of these specifiers:
1032-
1033-
* ``!s`` for :func:`str`
1034-
* ``!r`` for :func:`repr`
1035-
* ``!a`` for :func:`ascii`
1036-
1037-
For example::
1019+
>>> field_size = 20
1020+
>>> f'{color:-^{field_size}s}'
1021+
'--------blue--------'
10381022

1039-
>>> f'{one_third!r} is {one_third!s}'
1040-
'Fraction(1, 3) is 1/3'
1023+
These nested fields may include their own conversion fields and
1024+
:ref:`format specifiers <formatspec>`::
10411025

1042-
>>> string = "¡kočka 😸!"
1043-
>>> f'{string = !a}'
1044-
"string = '\\xa1ko\\u010dka \\U0001f638!'"
1026+
>>> number = 3
1027+
>>> f'{number:{field_size}}'
1028+
' 3'
1029+
>>> f'{number:{field_size:05}}'
1030+
'00000000000000000003'
10451031

1032+
However, these nested fields may not include more deeply nested replacement
1033+
fields.
10461034

1047-
Format specifier
1048-
^^^^^^^^^^^^^^^^
1035+
Formatted string literals may be concatenated, but replacement fields
1036+
cannot be split across literals.
1037+
For example, the following is a single f-string::
10491038

1050-
After the expression has been evaluated, and possibly converted using an
1051-
explicit conversion specifier, it is formatted using the :func:`format` function.
1052-
If the replacement field includes a *format specifier*, an arbitrary string
1053-
introduced by a colon (``:``), the specifier is passed to :func:`!format`
1054-
as the second argument.
1055-
The result of :func:`!format` is then used as the final value for the
1056-
replacement field. For example::
1039+
>>> f'{' '}'
1040+
' '
10571041

1058-
>>> f'{one_third:.6f}'
1059-
'0.333333'
1060-
>>> f'{one_third:_^+10}'
1061-
'___+1/3___'
1062-
>>> >>> f'{one_third!r:_^20}'
1063-
'___Fraction(1, 3)___'
1064-
>>> f'{one_third = :~>10}~'
1065-
'one_third = ~~~~~~~1/3~'
1042+
It is equivalent to ``f'{" "}'``, rather than ``f'{' "}"``.
10661043

10671044

10681045
Formal grammar
@@ -1116,38 +1093,6 @@ Formal grammar
11161093
---------------
11171094

11181095

1119-
1120-
1121-
When the equal sign ``'='`` is provided, the output will have the expression
1122-
text, the ``'='`` and the evaluated value. Spaces after the opening brace
1123-
``'{'``, within the expression and after the ``'='`` are all retained in the
1124-
output. By default, the ``'='`` causes the :func:`repr` of the expression to be
1125-
provided, unless there is a format specified. When a format is specified it
1126-
defaults to the :func:`str` of the expression unless a conversion ``'!r'`` is
1127-
declared.
1128-
1129-
.. versionadded:: 3.8
1130-
The equal sign ``'='``.
1131-
1132-
If a conversion is specified, the result of evaluating the expression
1133-
is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
1134-
the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
1135-
1136-
The result is then formatted using the :func:`format` protocol. The
1137-
format specifier is passed to the :meth:`~object.__format__` method of the
1138-
expression or conversion result. An empty string is passed when the
1139-
format specifier is omitted. The formatted result is then included in
1140-
the final value of the whole string.
1141-
1142-
Top-level format specifiers may include nested replacement fields. These nested
1143-
fields may include their own conversion fields and :ref:`format specifiers
1144-
<formatspec>`, but may not include more deeply nested replacement fields. The
1145-
:ref:`format specifier mini-language <formatspec>` is the same as that used by
1146-
the :meth:`str.format` method.
1147-
1148-
Formatted string literals may be concatenated, but replacement fields
1149-
cannot be split across literals.
1150-
11511096
Some examples of formatted string literals::
11521097

11531098
>>> name = "Fred"
@@ -1219,6 +1164,7 @@ include expressions.
12191164
See also :pep:`498` for the proposal that added formatted string literals,
12201165
and :meth:`str.format`, which uses a related format string mechanism.
12211166

1167+
12221168
.. _t-strings:
12231169
.. _template-string-literals:
12241170

0 commit comments

Comments
 (0)