@@ -2658,194 +2658,138 @@ that ``'\0'`` is the end of the string.
2658
2658
2659
2659
2660
2660
.. 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
2666
2666
single: interpolated string literal
2667
2667
single: string; formatted literal
2668
2668
single: string; interpolated literal
2669
- single: f-string
2670
- single: fstring
2671
2669
single: {} (curly brackets); in formatted string literal
2672
- single: ! (exclamation); in formatted string literal
2670
+ single: ! (exclamation mark ); in formatted string literal
2673
2671
single: : (colon); in formatted string literal
2674
2672
single: = (equals); in debug string literal
2675
- .. _f-string-formated-string-literal :
2676
2673
2677
- `` f-string ``- Formatted String Literal
2674
+ Formatted String Literals (f-strings)
2678
2675
-------------------------------------
2676
+
2679
2677
.. versionadded :: 3.6
2680
2678
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!'
2686
2693
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:
2691
2695
2692
- It is also possible to have a multi line string.::
2696
+ .. code-block :: pycon
2693
2697
2694
2698
>>> f'''This is a string
2695
2699
... on two lines'''
2696
2700
'This is a string\non two lines'
2697
2701
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:
2731
2704
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
2735
2706
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!'
2743
2710
2744
- : :
2711
+ To include a literal `` { `` or `` } ``, use a double bracket :
2745
2712
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
2751
2714
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'
2753
2718
2754
- >>> f"now={now}"
2755
- 'now=2020-07-28 04:33:08.629606'
2719
+ Functions can also be used, and :ref: `format specifier <formatstrings >`:
2756
2720
2757
- The new way to do this is to use the equal sign `` = `` after the expression.
2721
+ .. code-block :: pycon
2758
2722
2759
- .. versionadded :: 3.8
2723
+ >>> from math import sqrt
2724
+ >>> f'√2 \N{ALMOST EQUAL TO} {sqrt(2):.5f}'
2725
+ '√2 ≈ 1.41421'
2760
2726
2761
- : :
2727
+ Any non-string expression is converted using :func: ` str `, by default :
2762
2728
2763
- >>> f"{now = }" # spaces within braces are maintained.
2764
- 'now = datetime.datetime(2020, 7, 28, 4, 33, 8, 629606)'
2729
+ .. code-block :: pycon
2765
2730
2731
+ >>> from fractions import Fraction
2732
+ >>> f'{Fraction(1, 3)}'
2733
+ '1/3'
2766
2734
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 :
2769
2737
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
+ ========== ==============
2772
2745
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:
2835
2747
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:
2840
2764
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:
2843
2783
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___'
2847
2789
2848
2790
2791
+ .. index ::
2792
+ single: buffer protocol; binary sequence types
2849
2793
2850
2794
.. _binaryseq :
2851
2795
0 commit comments