13 2.4. Literals The Python Language Reference, Release 3.9.5 calls$_{str()}$ on the result,$_{'!r'}$ calls$_{repr()}$ , and$_{'!a'}$ calls$_{ascii()}$ . The result is then formatted using the$_{format()}$ protocol. The format specifier is passed to the$_{__format__()}$ method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string. Top-level format specifiers may include nested replacement fields. These nested fields may include their own con- version fields and format specifiers, but may not include more deeply-nested replacement fields. The format specifier mini-language is the same as that used by the str.format() method. Formatted string literals may be concatenated, but replacement fields cannot be split across literals. Some examples of formatted string literals: A consequence of sharing the same syntax as regular string literals is that characters in the replacement fields must not conflict with the quoting used in the outer formatted string literal: Backslashes are not allowed in format expressions and will raise an error: To include a value in which a backslash escape is required, create a temporary variable. Formatted string literals cannot be used as docstrings, even if they do not include expressions. (continues on next page) >>>def foo(): ... f"Not a docstring" f"abc { a["x"] } def" # error: outer string literal ended prematurely f"abc { a['x'] } def" # workaround: use different quoting >>> newline =ord(' ') >>> f"newline: { newline } " 'newline: 10' >>> name ="Fred " >>> f"He said his name is { name !r} ." "He said his name is 'Fred'." >>> f"He said his name is { repr(name) } ." # repr() is equivalent to !r "He said his name is 'Fred'." >>> width =10 >>> precision =4 >>> value=decimal.Decimal( "12.34567 ") >>> f"result: { value :{ width } . { precision }} " # nested fields 'result: 12.35' >>> today =datetime(year=2017 , month=1, day=27 ) >>> f" { today : %B %d, %Y } " # using date format specifier 'January 27, 2017' >>> f" { today =: %B %d, %Y } " # using date format specifier and debugging 'today=January 27, 2017' >>> number =1024 >>> f" { number : #0x } " # using integer format specifier '0x400' >>> foo ="bar" >>> f" { foo = } " # preserves whitespace " foo = 'bar'" >>> line ="The mill's closed" >>> f" { line = } " 'line = "The mill\'s closed"' >>> f" { line = : 20 } " "line = The mill's closed " >>> f" { line = !r: 20 } " 'line = "The mill\'s closed" ' f"newline: { ord(' ') } " # raises SyntaxError