8000 gh-85583: Add overview of formatted string literals (f-strings) to ``str`` by AA-Turner · Pull Request #132689 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Use doctest directives
  • Loading branch information
AA-Turner committed Apr 20, 2025
commit 62af72295f4468b99d52fb06952a7bc2f260ce0d
18 changes: 9 additions & 9 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2491,7 +2491,7 @@ These expressions are evaluated at runtime, similarly to :meth:`str.format`,
and are converted into regular :class:`str` objects.
For example:

.. code-block:: pycon
.. doctest::

>>> who = 'nobody'
>>> nationality = 'Spanish'
Expand All @@ -2500,7 +2500,7 @@ For example:

It is also possible to use a multi line f-string:

.. code-block:: pycon
.. doctest::

>>> f'''This is a string
... on two lines'''
Expand All @@ -2509,31 +2509,31 @@ It is also possible to use a multi line f-string:
A single opening curly bracket, ``'{'``, marks a *replacement field* that
can contain any Python expression:

.. code-block:: pycon
.. doctest::

>>> nationality = 'Spanish'
>>> f'The {nationality} Inquisition!'
'The Spanish Inquisition!'

To include a literal ``{`` or ``}``, use a double bracket:

.. code-block:: pycon
.. doctest::

>>> x = 42
>>> f'{{x}} is {x}'
'{x} is 42'

Functions can also be used, and :ref:`format specifier <formatstrings>`:

.. code-block:: pycon
.. doctest::

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

Any non-string expression is converted using :func:`str`, by default:

.. code-block:: pycon
.. doctest::

>>> from fractions import Fraction
>>> f'{Fraction(1, 3)}'
Expand All @@ -2552,7 +2552,7 @@ Conversion Meaning

For example:

.. code-block:: pycon
.. doctest::

>>> from fractions import Fraction
>>> f'{Fraction(1, 3)!s}'
Expand All @@ -2569,7 +2569,7 @@ This preserves spaces within the brackets, and can be used with a converter.
By default, the debugging operator uses the :func:`repr` (``!r``) conversion.
For example:

.. code-block:: pycon
.. doctest::

>>> from fractions import Fraction
>>> calculation = Fraction(1, 3)
Expand All @@ -2588,7 +2588,7 @@ or the empty string if no format specifier is given.
The formatted result is then used as the final value for the replacement field.
For example:

.. code-block:: pycon
.. doctest::

>>> from fractions import Fraction
>>> f'{Fraction(1, 7):.6f}'
Expand Down
Loading
0