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
Next Next commit
Add overview of formatted string literals (f-strings) to `str
Co-authored-by: Ezio Melotti <ezio.melotti@gmail.com>
Originally-authored-by: amaajemyfren@users.noreply.github.com
  • Loading branch information
AA-Turner and ezio-melotti committed Apr 18, 2025
commit 8d4bf9c9ca790070b91a01042d6ada5680047f3f
130 changes: 130 additions & 0 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2456,6 +2456,136 @@
'-0042'


.. index::
single: ! formatted string literal
single: formatted string literals
single: ! f-string
single: f-strings
single: fstring
single: interpolated string literal
single: string; formatted literal
single: string; interpolated literal
single: {} (curly brackets); in formatted string literal
single: ! (exclamation mark); in formatted string literal
single: : (colon); in formatted string literal
single: = (equals); for help in debugging using string literals

Formatted String Literals (f-strings)
-------------------------------------

.. versionadded:: 3.6

An :dfn:`f-string` (formally a :dfn:`formatted string literal`) is
a string literal that is prefixed with ``f`` or ``F``.
This type of string literal allows embedding arbitrary Python expressions
within *replacement fields*, which are delimited by curly brackets (``{}``).
These expressions are evaluated at runtime, similarly to :meth:`str.format`,
and are converted into regular :class:`str` objects.
For example:

.. code-block:: pycon

>>> who = 'nobody'
>>> nationality = 'Spanish'
>>> f'{who.title()} expects the {nationality} Inquisition!'
'Nobody expects the Spanish Inquisition!'

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

.. code-block:: pycon

>>> f'''This is a string
... on two lines'''
'This is a string\non two lines'

A single opening curly bracket, ``'{'``, marks a *replacement field* that
can contain any Python expression:

.. code-block:: pycon

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

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

.. code-block:: pycon

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

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

.. code-block:: pycon

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

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

.. code-block:: pycon

>>> from fractions import Fraction
>>> f'{Fraction(1, 3)}'
'1/3'

To use an explicit conversion, use the ``!`` (exclamation mark) operator,
followed by any of the valid formats, which are:

========== ==============
Conversion Meaning
========== ==============
``!a`` :func:`ascii`
``!r`` :func:`repr`
``!s`` :func:`str`
========== ==============

For example:

.. code-block:: pycon

>>> from fractions import Fraction
>>> f'{Fraction(1, 3)!s}'
'1/3'
>>> f'{Fraction(1, 3)!r}'
'Fraction(1, 3)'
>>> question = '¿Dónde está el Presidente?'
>>> print(f'{question!a}')
'\xbfD\xf3nde est\xe1 el Presidente?'

While debugging it may be helpful to see both the expression and its value,
using the equals sign (``=``) after the expression.
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

>>> from fractions import Fraction
>>> calculation = Fraction(1, 3)
>>> f'{calculation=}'
'calculation=Fraction(1, 3)'
>>> f'{calculation = }'
'calculation = Fraction(1, 3)'
>>> f'{calculation = !s}'
'calculation = 1/3'

Once the output has been evaluated, it can be formatted using a

Check warning on line 2575 in Doc/library/stdtypes.rst

View workflow job for this annotation

GitHub Actions / Docs / Docs

py:meth reference target not found: __format__ [ref.meth]
:ref:`format specifier <formatstrings>` following a colon (``':'``).
After the expression has been evaluated, and possibly converted to a string,
the :meth:`__format__` method of the result is called with the format specifier,
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:

>>> from fractions import Fraction
>>> f'{Fraction(1, 7):.6f}'
'0.142857'
>>> f'{Fraction(1, 7):_^+10}'
'___+1/7___'


.. _old-string-formatting:

Expand Down
Loading
0