Skip to content

Commit d01da75

Browse files
committed
Major rewrite, modernisation
1 parent 9d6ac90 commit d01da75

File tree

2 files changed

+99
-155
lines changed

2 files changed

+99
-155
lines changed

Doc/library/dis.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,7 +1667,7 @@ iterations of the loop.
16671667
* ``oparg == 2``: call :func:`repr` on *value*
16681668
* ``oparg == 3``: call :func:`ascii` on *value*
16691669

1670-
Used for implementing formatted literal strings (f-strings).
1670+
Used for implementing formatted string literals (f-strings).
16711671

16721672
.. versionadded:: 3.13
16731673

@@ -1680,7 +1680,7 @@ iterations of the loop.
16801680
result = value.__format__("")
16811681
STACK.append(result)
16821682

1683-
Used for implementing formatted literal strings (f-strings).
1683+
Used for implementing formatted string literals (f-strings).
16841684

16851685
.. versionadded:: 3.13
16861686

@@ -1693,7 +1693,7 @@ iterations of the loop.
16931693
result = value.__format__(spec)
16941694
STACK.append(result)
16951695

1696-
Used for implementing formatted literal strings (f-strings).
1696+
Used for implementing formatted string literals (f-strings).
16971697

16981698
.. versionadded:: 3.13
16991699

Doc/library/stdtypes.rst

Lines changed: 96 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -2658,194 +2658,138 @@ that ``'\0'`` is the end of the string.
26582658

26592659

26602660
.. index::
2661-
single: buffer protocol; binary sequence types
2662-
2663-
2664-
.. index::
2665-
single: formatted string literal
2661+
single: ! formatted string literal
2662+
single: formatted string literals
2663+
single: ! f-string
2664+
single: f-strings
2665+
single: fstring
26662666
single: interpolated string literal
26672667
single: string; formatted literal
26682668
single: string; interpolated literal
2669-
single: f-string
2670-
single: fstring
26712669
single: {} (curly brackets); in formatted string literal
2672-
single: ! (exclamation); in formatted string literal
2670+
single: ! (exclamation mark); in formatted string literal
26732671
single: : (colon); in formatted string literal
26742672
single: = (equals); in debug string literal
2675-
.. _f-string-formated-string-literal:
26762673

2677-
``f-string``-Formatted String Literal
2674+
Formatted String Literals (f-strings)
26782675
-------------------------------------
2676+
26792677
.. versionadded:: 3.6
26802678

2681-
A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal that
2682-
is prefixed with ``f`` or ``F``. These strings may contain replacement
2683-
fields, which are expressions delimited by curly braces ``{}``. While other
2684-
string literals always have a constant value, formatted strings are expressions
2685-
evaluated at run time.::
2679+
An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
2680+
a string literal that is prefixed with ``f`` or ``F``.
2681+
This type of string literal allows embedding arbitrary Python expressions
2682+
within *replacement fields*, which are delimited by curly brackets (``{}``).
2683+
These expressions are evaluated at runtime, similarly to :meth:`str.format`,
2684+
and are converted into regular :class:`str` objects.
2685+
For example:
2686+
2687+
.. code-block:: pycon
2688+
2689+
>>> who = 'nobody'
2690+
>>> nationality = 'Spanish'
2691+
>>> f'{who.title()} expects the {nationality} Inquisition!'
2692+
'Nobody expects the Spanish Inquisition!'
26862693
2687-
>>> f"This is an f-string"
2688-
'This is an f-string'
2689-
>>> F"This is also an f-string"
2690-
'This is also an f-string'
2694+
It is also possible to use a multi line f-string:
26912695

2692-
It is also possible to have a multi line string.::
2696+
.. code-block:: pycon
26932697
26942698
>>> f'''This is a string
26952699
... on two lines'''
26962700
'This is a string\non two lines'
26972701
2698-
A single opening curly bracket, ``'{'``, marks a replacement field that contains
2699-
a python expression.::
2700-
2701-
>>> name = "Fred"
2702-
>>> f"He said his name is {name}"
2703-
'He said his name is Fred'
2704-
2705-
Everything outside the braces is treated as a literal::
2706-
2707-
>>> a = 4
2708-
>>> b = 3
2709-
>>> f"The product of {a} and {b} is {a * b}"
2710-
'The product of 4 and 3 is 12'
2711-
2712-
If you want to include a literal ``{`` or ``}``, you can double the curly
2713-
brackets to escape them::
2714-
2715-
>>> f'{{a}} is {a}'
2716-
'{a} is 4'
2717-
2718-
Functions can also be used.::
2719-
2720-
>>> s = "Python"
2721-
>>> f"The string {s.upper()} contains {len(s)} characters."
2722-
'The string PYTHON contains 6 characters.'
2723-
2724-
By default the :func:`str` format of a variable is presented when using
2725-
f-strings::
2726-
2727-
>>> import datetime
2728-
>>> now = datetime.datetime.now()
2729-
>>> f"{now}"
2730-
'2020-07-28 04:33:08.629606'
2702+
A single opening curly bracket, ``'{'``, marks a *replacement field* that
2703+
can contain any Python expression:
27312704

2732-
Note that this is the :func:`str` format of a :mod:`datetime`. To show a
2733-
different format you use a conversion. There are three conversions beginning
2734-
with the ``'!'`` (exclamation) mark.
2705+
.. code-block:: pycon
27352706
2736-
============ ===============
2737-
Conversion Meaning
2738-
============ ===============
2739-
``!r`` :func:`repr`
2740-
``!s`` :func:`str`
2741-
``!a`` :func:`ascii`
2742-
============ ===============
2707+
>>> nationality = 'Spanish'
2708+
>>> f'The {name} Inquisition!'
2709+
'The Spanish Inquisition!'
27432710
2744-
::
2711+
To include a literal ``{`` or ``}``, use a double bracket:
27452712

2746-
>>> f"{now!r}"
2747-
'datetime.datetime(2020, 7, 28, 4, 33, 8, 629606)'
2748-
>>> hello = "你好"
2749-
>>> f"The ASCII version of {hello!r} is {hello!a}."
2750-
"The ASCII version of '你好' is '\\u4f60\\u597d'."
2713+
.. code-block:: pycon
27512714
2752-
While debugging it may be helpful to see both the expression and its value.::
2715+
>>> x = 42
2716+
>>> f'{{x}} is {x}'
2717+
'{x} is 42'
27532718
2754-
>>> f"now={now}"
2755-
'now=2020-07-28 04:33:08.629606'
2719+
Functions can also be used, and :ref:`format specifier <formatstrings>`:
27562720

2757-
The new way to do this is to use the equal sign ``=`` after the expression.
2721+
.. code-block:: pycon
27582722
2759-
.. versionadded:: 3.8
2723+
>>> from math import sqrt
2724+
>>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
2725+
'√2 ≈ 1.41421'
27602726
2761-
::
2727+
Any non-string expression is converted using :func:`str`, by default:
27622728

2763-
>>> f"{now = }" # spaces within braces are maintained.
2764-
'now = datetime.datetime(2020, 7, 28, 4, 33, 8, 629606)'
2729+
.. code-block:: pycon
27652730
2731+
>>> from fractions import Fraction
2732+
>>> f'{Fraction(1, 3)}'
2733+
'1/3'
27662734
2767-
When used by its own, the debugging operator ``=``, outputs the :func:`repr` of
2768-
the expression. A converter can be used to change it::
2735+
To use an explicit conversion, use the ``!`` (exclamation mark) operator,
2736+
followed by any of the valid formats, which are:
27692737

2770-
>>> f"{now=!s}"
2771-
'now=2020-07-28 04:33:08.629606'
2738+
========== ==============
2739+
Conversion Meaning
2740+
========== ==============
2741+
``!a`` :func:`ascii`
2742+
``!r`` :func:`repr`
2743+
``!s`` :func:`str`
2744+
========== ==============
27722745

2773-
Once the output has been evaluated it can then be formatted using a formatting
2774-
specifier that is appended preceeded by a ``':'`` (colon).
2775-
2776-
The format specifier is passed to the :meth:`__format__` method of the
2777-
expression or conversion result. An empty string is passed when the format
2778-
specifier is omitted. The formatted result is then returned as the final value
2779-
of the whole string.
2780-
2781-
As an example for :mod:`datetime` we could use format specifiers described in
2782-
:ref:`strftime-strptime-behavior`::
2783-
2784-
>>> f"{now:%B %d, %Y}"
2785-
'July 28, 2020'
2786-
2787-
Most built-in types will comply with the :ref:`formatspec`::
2788-
2789-
>>> num = 12.3456
2790-
>>> f"{num:20}"
2791-
' 12.3456'
2792-
>>> f"{num:<20}"
2793-
'12.3456 '
2794-
>>> f"{num:e}"
2795-
'1.234560e+01'
2796-
2797-
When a format specifier is given together with the equal sign ``'='`` the
2798-
default conversion for the expressions' is :func:`str`. Conversion can be used
2799-
to show the :func:`repr` form::
2800-
2801-
>>> import decimal
2802-
>>> value = decimal.Decimal("12.34567")
2803-
>>> f"{value=}"
2804-
"value=Decimal('12.34567')"
2805-
>>> f"{value=:20}"
2806-
'value= 12.34567'
2807-
>>> f"{value=!r:20}"
2808-
"value=Decimal('12.34567') "
2809-
2810-
Formatted string literals cannot be used as docstrings, even if they do not
2811-
include expressions.::
2812-
2813-
>>> def foo():
2814-
... f"Not a docstring"
2815-
...
2816-
>>> print(foo.__doc__)
2817-
None
2818-
2819-
A consequence of sharing the same syntax as regular string literals is
2820-
that characters in the replacement fields must not conflict with the
2821-
quoting used in the outer formatted string literal::
2822-
2823-
>>> a = {"Terry":"Jones", "John":"Cleese", "x":"Gilliam", "Eric":"Idle"}
2824-
>>> f"abc {a["x"]} def"
2825-
File "<stdin>", line 1
2826-
f"abc {a["x"]} def"
2827-
^
2828-
SyntaxError: f-string: unmatched '['
2829-
2830-
>>> f"abc {a['x']} def" # workaround: use different quoting
2831-
'abc Gilliam def'
2832-
2833-
Backslashes are not allowed in format expressions and will raise
2834-
an error::
2746+
For example:
28352747

2836-
>>> f'{ord("\n")}'
2837-
File "<stdin>", line 1
2838-
f'{ord("\n")}'
2839-
SyntaxError: f-string expression part cannot include a backslash
2748+
.. code-block:: pycon
2749+
2750+
>>> from fractions import Fraction
2751+
>>> f'{Fraction(1, 3)!s}'
2752+
'1/3'
2753+
>>> f'{Fraction(1, 3)!r}'
2754+
'Fraction(1, 3)'
2755+
>>> question = '¿Dónde está el Presidente?'
2756+
>>> print(f'{question!a}')
2757+
'\xbfD\xf3nde est\xe1 el Presidente?'
2758+
2759+
While debugging it may be helpful to see both the expression and its value,
2760+
using the equals sign (``=``) after the expression.
2761+
This preserves spaces within the brackets, and can be used with a converter.
2762+
By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
2763+
For example:
28402764

2841-
To include a value in which a backslash escape is required, create
2842-
a temporary variable.::
2765+
.. code-block:: pycon
2766+
2767+
>>> from fractions import Fraction
2768+
>>> calculation = Fraction(1, 3)
2769+
>>> f'{calculation=}'
2770+
'calculation=Fraction(1, 3)'
2771+
>>> f'{calculation = }'
2772+
'calculation = Fraction(1, 3)'
2773+
>>> f'{calculation = !s}'
2774+
'calculation = 1/3'
2775+
2776+
Once the output has been evaluated, it can be formatted using a
2777+
:ref:`format specifier <formatstrings>` following a colon (``':'``).
2778+
After the expression has been evaluated, and possibly converted to a string,
2779+
the :meth:`__format__` method of the result is called with the format specifier,
2780+
or the empty string if no format specifier is given.
2781+
The formatted result is then used as the final value for the replacement field.
2782+
For example:
28432783

2844-
>>> newline = ord('\n')
2845-
>>> f"newline: {newline}"
2846-
'newline: 10'
2784+
>>> from fractions import Fraction
2785+
>>> f'{Fraction(1, 7):.6f}'
2786+
'0.142857'
2787+
>>> f'{Fraction(1, 7):_^+10}'
2788+
'___+1/7___'
28472789

28482790

2791+
.. index::
2792+
single: buffer protocol; binary sequence types
28492793

28502794
.. _binaryseq:
28512795

0 commit comments

Comments
 (0)