@@ -405,7 +405,8 @@ String literals are described by the following lexical definitions:
405405
406406.. productionlist ::
407407 stringliteral: [`stringprefix `](`shortstring ` | `longstring `)
408- stringprefix: "r" | "u" | "R" | "U"
408+ stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
409+ : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
409410 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
410411 longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
411412 shortstringitem: `shortstringchar ` | `stringescapeseq `
@@ -464,6 +465,11 @@ is not supported.
464465 to simplify the maintenance of dual Python 2.x and 3.x codebases.
465466 See :pep: `414 ` for more information.
466467
468+ A string literal with ``'f' `` or ``'F' `` in its prefix is a
469+ :dfn: `formatted string literal `; see :ref: `f-strings `. The ``'f' `` may be
470+ combined with ``'r' ``, but not with ``'b' `` or ``'u' ``, therefore raw
471+ formatted strings are possible, but formatted bytes literals are not.
472+
467473In triple-quoted literals, unescaped newlines and quotes are allowed (and are
468474retained), except that three unescaped quotes in a row terminate the literal. (A
469475"quote" is the character used to open the literal, i.e. either ``' `` or ``" ``.)
@@ -584,7 +590,105 @@ comments to parts of strings, for example::
584590Note that this feature is defined at the syntactical level, but implemented at
585591compile time. The '+' operator must be used to concatenate string expressions
586592at run time. Also note that literal concatenation can use different quoting
587- styles for each component (even mixing raw strings and triple quoted strings).
593+ styles for each component (even mixing raw strings and triple quoted strings),
594+ and formatted string literals may be concatenated with plain string literals.
595+
596+
597+ .. index ::
598+ single: formatted string literal
599+ single: interpolated string literal
600+ single: string; formatted literal
601+ single: string; interpolated literal
602+ single: f-string
603+ .. _f-strings :
604+
605+ Formatted string literals
606+ -------------------------
607+
608+ .. versionadded :: 3.6
609+
610+ A :dfn: `formatted string literal ` or :dfn: `f-string ` is a string literal
611+ that is prefixed with ``'f' `` or ``'F' ``. These strings may contain
612+ replacement fields, which are expressions delimited by curly braces ``{} ``.
613+ While other string literals always have a constant value, formatted strings
614+ are really expressions evaluated at run time.
615+
616+ Escape sequences are decoded like in ordinary string literals (except when
617+ a literal is also marked as a raw string). After decoding, the grammar
618+ for the contents of the string is:
619+
620+ .. productionlist ::
621+ f_string: (`literal_char ` | "{{" | "}}" | `replacement_field `)*
622+ replacement_field: "{" `f_expression ` ["!" `conversion `] [":" `format_spec `] "}"
623+ f_expression: `conditional_expression ` ("," `conditional_expression `)* [","]
624+ : | `yield_expression `
625+ conversion: "s" | "r" | "a"
626+ format_spec: (`literal_char ` | NULL | `replacement_field `)*
627+ literal_char: <any code point except "{", "}" or NULL>
628+
629+ The parts of the string outside curly braces are treated literally,
630+ except that any doubled curly braces ``'{{' `` or ``'}}' `` are replaced
631+ with the corresponding single curly brace. A single opening curly
632+ bracket ``'{' `` marks a replacement field, which starts with a
633+ Python expression. After the expression, there may be a conversion field,
634+ introduced by an exclamation point ``'!' ``. A format specifier may also
635+ be appended, introduced by a colon ``':' ``. A replacement field ends
636+ with a closing curly bracket ``'}' ``.
637+
638+ Expressions in formatted string literals are treated like regular
639+ Python expressions surrounded by parentheses, with a few exceptions.
640+ An empty expression is not allowed, and a :keyword: `lambda ` expression
641+ must be surrounded by explicit parentheses. Replacement expressions
642+ can contain line breaks (e.g. in triple-quoted strings), but they
643+ cannot contain comments. Each expression is evaluated in the context
644+ where the formatted string literal appears, in order from left to right.
645+
646+ If a conversion is specified, the result of evaluating the expression
647+ is converted before formatting. Conversion ``'!s' `` calls :func: `str ` on
648+ the result, ``'!r' `` calls :func: `repr `, and ``'!a' `` calls :func: `ascii `.
649+
650+ The result is then formatted using the :func: `format ` protocol. The
651+ format specifier is passed to the :meth: `__format__ ` method of the
652+ expression or conversion result. An empty string is passed when the
653+ format specifier is omitted. The formatted result is then included in
654+ the final value of the whole string.
655+
656+ Top-level format specifiers may include nested replacement fields.
657+ These nested fields may include their own conversion fields and
658+ format specifiers, but may not include more deeply-nested replacement fields.
659+
660+ Formatted string literals may be concatenated, but replacement fields
661+ cannot be split across literals.
662+
663+ Some examples of formatted string literals::
664+
665+ >>> name = "Fred"
666+ >>> f"He said his name is {name!r}."
667+ "He said his name is 'Fred'."
668+ >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
669+ "He said his name is 'Fred'."
670+ >>> width = 10
671+ >>> precision = 4
672+ >>> value = decimal.Decimal("12.34567")
673+ >>> f"result: {value:{width}.{precision}}" # nested fields
674+ 'result: 12.35'
675+
676+ A consequence of sharing the same syntax as regular string literals is
677+ that characters in the replacement fields must not conflict with the
678+ quoting used in the outer formatted string literal. Also, escape
679+ sequences normally apply to the outer formatted string literal,
680+ rather than inner string literals::
681+
682+ f"abc {a["x"]} def" # error: outer string literal ended prematurely
683+ f"abc {a[\"x\"]} def" # workaround: escape the inner quotes
684+ f"abc {a['x']} def" # workaround: use different quoting
685+
686+ f"newline: {ord('\n')}" # error: literal line break in inner string
687+ f"newline: {ord('\\n')}" # workaround: double escaping
688+ fr"newline: {ord('\n')}" # workaround: raw outer string
689+
690+ See also :pep: `498 ` for the proposal that added formatted string literals,
691+ and :meth: `str.format `, which uses a related format string mechanism.
588692
589693
590694.. _numbers :
0 commit comments