Skip to content

Commit 9d6ac90

Browse files
amaajemyfrenezio-melotti
authored andcommitted
Improve and consolidate f-strings docs
Co-authored-by: Ezio Melotti <[email protected]>
1 parent e77d678 commit 9d6ac90

File tree

1 file changed

+187
-0
lines changed

1 file changed

+187
-0
lines changed

Doc/library/stdtypes.rst

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2660,6 +2660,193 @@ that ``'\0'`` is the end of the string.
26602660
.. index::
26612661
single: buffer protocol; binary sequence types
26622662

2663+
2664+
.. index::
2665+
single: formatted string literal
2666+
single: interpolated string literal
2667+
single: string; formatted literal
2668+
single: string; interpolated literal
2669+
single: f-string
2670+
single: fstring
2671+
single: {} (curly brackets); in formatted string literal
2672+
single: ! (exclamation); in formatted string literal
2673+
single: : (colon); in formatted string literal
2674+
single: = (equals); in debug string literal
2675+
.. _f-string-formated-string-literal:
2676+
2677+
``f-string``-Formatted String Literal
2678+
-------------------------------------
2679+
.. versionadded:: 3.6
2680+
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.::
2686+
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'
2691+
2692+
It is also possible to have a multi line string.::
2693+
2694+
>>> f'''This is a string
2695+
... on two lines'''
2696+
'This is a string\non two lines'
2697+
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'
2731+
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.
2735+
2736+
============ ===============
2737+
Conversion Meaning
2738+
============ ===============
2739+
``!r`` :func:`repr`
2740+
``!s`` :func:`str`
2741+
``!a`` :func:`ascii`
2742+
============ ===============
2743+
2744+
::
2745+
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'."
2751+
2752+
While debugging it may be helpful to see both the expression and its value.::
2753+
2754+
>>> f"now={now}"
2755+
'now=2020-07-28 04:33:08.629606'
2756+
2757+
The new way to do this is to use the equal sign ``=`` after the expression.
2758+
2759+
.. versionadded:: 3.8
2760+
2761+
::
2762+
2763+
>>> f"{now = }" # spaces within braces are maintained.
2764+
'now = datetime.datetime(2020, 7, 28, 4, 33, 8, 629606)'
2765+
2766+
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::
2769+
2770+
>>> f"{now=!s}"
2771+
'now=2020-07-28 04:33:08.629606'
2772+
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::
2835+
2836+
>>> f'{ord("\n")}'
2837+
File "<stdin>", line 1
2838+
f'{ord("\n")}'
2839+
SyntaxError: f-string expression part cannot include a backslash
2840+
2841+
To include a value in which a backslash escape is required, create
2842+
a temporary variable.::
2843+
2844+
>>> newline = ord('\n')
2845+
>>> f"newline: {newline}"
2846+
'newline: 10'
2847+
2848+
2849+
26632850
.. _binaryseq:
26642851

26652852
Binary Sequence Types --- :class:`bytes`, :class:`bytearray`, :class:`memoryview`

0 commit comments

Comments
 (0)