Skip to content

Commit 2cd9bf4

Browse files
committed
f-strings can only be concatenated with themselves
1 parent 11e3731 commit 2cd9bf4

File tree

1 file changed

+23
-10
lines changed

1 file changed

+23
-10
lines changed

Doc/reference/expressions.rst

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -164,32 +164,45 @@ String literal concatenation
164164

165165
Multiple adjacent string or bytes literals (delimited by whitespace), possibly
166166
using different quoting conventions, are allowed, and their meaning is the same
167-
as their concatenation. Thus, ``"hello" 'world'`` is equivalent to
168-
``"helloworld"``.
167+
as their concatenation::
168+
169+
>>> "hello" 'world'
170+
"helloworld"
169171

170172
Formally:
171173

172174
.. grammar-snippet::
173175
:group: python-grammar
174176

175-
strings: ( `STRING` | fstring | tstring)+
177+
strings: ( `STRING` | fstring)+ | tstring+
176178

177179
Note that this feature is defined at the syntactical level, so it only works
178180
with literals.
179181
To concatenate string expressions at run time, the '+' operator may be used::
180182

181-
greeting = "Hello"
182-
space = " "
183-
name = "Blaise"
184-
print(greeting + space + name) # not: print(greeting space name)
183+
>>> greeting = "Hello"
184+
>>> space = " "
185+
>>> name = "Blaise"
186+
>>> print(greeting + space + name) # not: print(greeting space name)
187+
Hello Blaise
185188

186189
Also note that literal concatenation can freely mix raw strings,
187-
triple-quoted strings, and formatted or template string literals.
188-
However, bytes literals may not be combined with string literals of any kind.
190+
triple-quoted strings, and formatted string literals. For example::
191+
192+
>>> "Hello" r', ' f"{name}!"
193+
"Hello, Blaise!"
194+
195+
However, bytes literals may only be combined with other byte literals;
196+
not with string literals of any kind.
197+
Also, template string literals may only be combined with other template
198+
string literals::
199+
200+
>>> t"Hello" t"{name}!"
201+
Template(strings=('Hello', '!'), interpolations=(...))
189202

190203
This feature can be used to reduce the number of backslashes
191204
needed, to split long strings conveniently across long lines, or even to add
192-
comments to parts of strings, for example::
205+
comments to parts of strings. For example::
193206

194207
re.compile("[A-Za-z_]" # letter or underscore
195208
"[A-Za-z0-9_]*" # letter, digit or underscore

0 commit comments

Comments
 (0)