File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -679,17 +679,22 @@ Some examples of formatted string literals::
679679
680680A consequence of sharing the same syntax as regular string literals is
681681that characters in the replacement fields must not conflict with the
682- quoting used in the outer formatted string literal. Also, escape
683- sequences normally apply to the outer formatted string literal,
684- rather than inner string literals::
682+ quoting used in the outer formatted string literal::
685683
686684 f"abc {a["x"]} def" # error: outer string literal ended prematurely
687- f"abc {a[\"x\"]} def" # workaround: escape the inner quotes
688685 f"abc {a['x']} def" # workaround: use different quoting
689686
690- f"newline: {ord('\n')}" # error: literal line break in inner string
691- f"newline: {ord('\\n')}" # workaround: double escaping
692- fr"newline: {ord('\n')}" # workaround: raw outer string
687+ Backslashes are not allowed in format expressions and will raise
688+ an error::
689+
690+ f"newline: {ord('\n')}" # raises SyntaxError
691+
692+ To include a value in which a backslash escape is required, create
693+ a temporary variable.
694+
695+ >>> newline = ord (' \n ' )
696+ >>> f " newline: { newline} "
697+ 'newline: 10'
693698
694699See also :pep: `498 ` for the proposal that added formatted string literals,
695700and :meth: `str.format `, which uses a related format string mechanism.
Original file line number Diff line number Diff line change @@ -382,11 +382,14 @@ def test_no_backslashes_in_expression_part(self):
382382 ])
383383
384384 def test_no_escapes_for_braces (self ):
385- # \x7b is '{'. Make sure it doesn't start an expression.
386- self .assertEqual (f'\x7b 2}}' , '{2}' )
387- self .assertEqual (f'\x7b 2' , '{2' )
388- self .assertEqual (f'\u007b 2' , '{2' )
389- self .assertEqual (f'\N{LEFT CURLY BRACKET} 2\N{RIGHT CURLY BRACKET} ' , '{2}' )
385+ """
386+ Only literal curly braces begin an expression.
387+ """
388+ # \x7b is '{'.
389+ self .assertEqual (f'\x7b 1+1}}' , '{1+1}' )
390+ self .assertEqual (f'\x7b 1+1' , '{1+1' )
391+ self .assertEqual (f'\u007b 1+1' , '{1+1' )
392+ self .assertEqual (f'\N{LEFT CURLY BRACKET} 1+1\N{RIGHT CURLY BRACKET} ' , '{1+1}' )
390393
391394 def test_newlines_in_expressions (self ):
392395 self .assertEqual (f'{ 0 } ' , '0' )
You can’t perform that action at this time.
0 commit comments