[3.14] gh-135676: Lexical analysis: Reword String literals and related sections (GH-135942) (#137048)

Co-authored-by: Petr Viktorin <encukou@gmail.com>
Co-authored-by: Blaise Pabon <blaise@gmail.com>
Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
Co-authored-by: Adam Turner <9087854+AA-Turner@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2025-07-23 18:23:25 +02:00 committed by GitHub
parent 9f25781bf9
commit 4832ceaa78
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 443 additions and 206 deletions

View file

@ -133,13 +133,18 @@ Literals
Python supports string and bytes literals and various numeric literals:
.. productionlist:: python-grammar
literal: `stringliteral` | `bytesliteral` | `NUMBER`
.. grammar-snippet::
:group: python-grammar
literal: `strings` | `NUMBER`
Evaluation of a literal yields an object of the given type (string, bytes,
integer, floating-point number, complex number) with the given value. The value
may be approximated in the case of floating-point and imaginary (complex)
literals. See section :ref:`literals` for details.
literals.
See section :ref:`literals` for details.
See section :ref:`string-concatenation` for details on ``strings``.
.. index::
triple: immutable; data; type
@ -152,6 +157,58 @@ occurrence) may obtain the same object or a different object with the same
value.
.. _string-concatenation:
String literal concatenation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Multiple adjacent string or bytes literals (delimited by whitespace), possibly
using different quoting conventions, are allowed, and their meaning is the same
as their concatenation::
>>> "hello" 'world'
"helloworld"
Formally:
.. grammar-snippet::
:group: python-grammar
strings: ( `STRING` | fstring)+ | tstring+
This feature is defined at the syntactical level, so it only works with literals.
To concatenate string expressions at run time, the '+' operator may be used::
>>> greeting = "Hello"
>>> space = " "
>>> name = "Blaise"
>>> print(greeting + space + name) # not: print(greeting space name)
Hello Blaise
Literal concatenation can freely mix raw strings, triple-quoted strings,
and formatted string literals.
For example::
>>> "Hello" r', ' f"{name}!"
"Hello, Blaise!"
This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings. For example::
re.compile("[A-Za-z_]" # letter or underscore
"[A-Za-z0-9_]*" # letter, digit or underscore
)
However, bytes literals may only be combined with other byte literals;
not with string literals of any kind.
Also, template string literals may only be combined with other template
string literals::
>>> t"Hello" t"{name}!"
Template(strings=('Hello', '!'), interpolations=(...))
.. _parenthesized:
Parenthesized forms