Skip to content

gh-85583: Add overview of formatted string literals (f-strings) to str #132689

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 21, 2025
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
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