blob: e1d88eff959f631c0c79040b7ddf38ca53e88368 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _lexical:
3
4****************
5Lexical analysis
6****************
7
Georg Brandl57e3b682007-08-31 08:07:45 +00008.. index:: lexical analysis, parser, token
Georg Brandl116aa622007-08-15 14:28:22 +00009
10A Python program is read by a *parser*. Input to the parser is a stream of
11*tokens*, generated by the *lexical analyzer*. This chapter describes how the
12lexical analyzer breaks a file into tokens.
13
Georg Brandl57e3b682007-08-31 08:07:45 +000014Python reads program text as Unicode code points; the encoding of a source file
15can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120`
16for details. If the source file cannot be decoded, a :exc:`SyntaxError` is
17raised.
Georg Brandl116aa622007-08-15 14:28:22 +000018
19
20.. _line-structure:
21
22Line structure
23==============
24
Georg Brandl57e3b682007-08-31 08:07:45 +000025.. index:: line structure
Georg Brandl116aa622007-08-15 14:28:22 +000026
27A Python program is divided into a number of *logical lines*.
28
29
Georg Brandl57e3b682007-08-31 08:07:45 +000030.. _logical-lines:
Georg Brandl116aa622007-08-15 14:28:22 +000031
32Logical lines
33-------------
34
Georg Brandl57e3b682007-08-31 08:07:45 +000035.. index:: logical line, physical line, line joining, NEWLINE token
Georg Brandl116aa622007-08-15 14:28:22 +000036
37The end of a logical line is represented by the token NEWLINE. Statements
38cannot cross logical line boundaries except where NEWLINE is allowed by the
39syntax (e.g., between statements in compound statements). A logical line is
40constructed from one or more *physical lines* by following the explicit or
41implicit *line joining* rules.
42
43
Georg Brandl57e3b682007-08-31 08:07:45 +000044.. _physical-lines:
Georg Brandl116aa622007-08-15 14:28:22 +000045
46Physical lines
47--------------
48
49A physical line is a sequence of characters terminated by an end-of-line
Ammar Askar0aa17ee2018-06-09 16:49:39 -070050sequence. In source files and strings, any of the standard platform line
51termination sequences can be used - the Unix form using ASCII LF (linefeed),
52the Windows form using the ASCII sequence CR LF (return followed by linefeed),
53or the old Macintosh form using the ASCII CR (return) character. All of these
54forms can be used equally, regardless of platform. The end of input also serves
55as an implicit terminator for the final physical line.
Georg Brandl116aa622007-08-15 14:28:22 +000056
57When embedding Python, source code strings should be passed to Python APIs using
58the standard C conventions for newline characters (the ``\n`` character,
59representing ASCII LF, is the line terminator).
60
61
62.. _comments:
63
64Comments
65--------
66
Georg Brandl57e3b682007-08-31 08:07:45 +000067.. index:: comment, hash character
Georg Brandl116aa622007-08-15 14:28:22 +000068
69A comment starts with a hash character (``#``) that is not part of a string
70literal, and ends at the end of the physical line. A comment signifies the end
71of the logical line unless the implicit line joining rules are invoked. Comments
72are ignored by the syntax; they are not tokens.
73
74
75.. _encodings:
76
77Encoding declarations
78---------------------
79
R David Murrayf7f98182014-04-16 21:48:04 -040080.. index:: source character set, encoding declarations (source file)
Georg Brandl116aa622007-08-15 14:28:22 +000081
82If a comment in the first or second line of the Python script matches the
83regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
84encoding declaration; the first group of this expression names the encoding of
Robert Collins0b2833e2015-08-06 21:08:44 +120085the source code file. The encoding declaration must appear on a line of its
86own. If it is the second line, the first line must also be a comment-only line.
87The recommended forms of an encoding expression are ::
Georg Brandl116aa622007-08-15 14:28:22 +000088
89 # -*- coding: <encoding-name> -*-
90
91which is recognized also by GNU Emacs, and ::
92
93 # vim:fileencoding=<encoding-name>
94
Georg Brandl57e3b682007-08-31 08:07:45 +000095which is recognized by Bram Moolenaar's VIM.
96
97If no encoding declaration is found, the default encoding is UTF-8. In
98addition, if the first bytes of the file are the UTF-8 byte-order mark
99(``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported,
100among others, by Microsoft's :program:`notepad`).
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102If an encoding is declared, the encoding name must be recognized by Python. The
Georg Brandl57e3b682007-08-31 08:07:45 +0000103encoding is used for all lexical analysis, including string literals, comments
Robert Collins0b2833e2015-08-06 21:08:44 +1200104and identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000105
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000106.. XXX there should be a list of supported encodings.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108
109.. _explicit-joining:
110
111Explicit line joining
112---------------------
113
Georg Brandl57e3b682007-08-31 08:07:45 +0000114.. index:: physical line, line joining, line continuation, backslash character
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116Two or more physical lines may be joined into logical lines using backslash
117characters (``\``), as follows: when a physical line ends in a backslash that is
118not part of a string literal or comment, it is joined with the following forming
119a single logical line, deleting the backslash and the following end-of-line
Georg Brandl57e3b682007-08-31 08:07:45 +0000120character. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 if 1900 < year < 2100 and 1 <= month <= 12 \
123 and 1 <= day <= 31 and 0 <= hour < 24 \
124 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
125 return 1
126
127A line ending in a backslash cannot carry a comment. A backslash does not
128continue a comment. A backslash does not continue a token except for string
129literals (i.e., tokens other than string literals cannot be split across
130physical lines using a backslash). A backslash is illegal elsewhere on a line
131outside a string literal.
132
133
134.. _implicit-joining:
135
136Implicit line joining
137---------------------
138
139Expressions in parentheses, square brackets or curly braces can be split over
140more than one physical line without using backslashes. For example::
141
142 month_names = ['Januari', 'Februari', 'Maart', # These are the
143 'April', 'Mei', 'Juni', # Dutch names
144 'Juli', 'Augustus', 'September', # for the months
145 'Oktober', 'November', 'December'] # of the year
146
147Implicitly continued lines can carry comments. The indentation of the
148continuation lines is not important. Blank continuation lines are allowed.
149There is no NEWLINE token between implicit continuation lines. Implicitly
150continued lines can also occur within triple-quoted strings (see below); in that
151case they cannot carry comments.
152
153
154.. _blank-lines:
155
156Blank lines
157-----------
158
159.. index:: single: blank line
160
161A logical line that contains only spaces, tabs, formfeeds and possibly a
162comment, is ignored (i.e., no NEWLINE token is generated). During interactive
163input of statements, handling of a blank line may differ depending on the
Georg Brandl57e3b682007-08-31 08:07:45 +0000164implementation of the read-eval-print loop. In the standard interactive
165interpreter, an entirely blank logical line (i.e. one containing not even
166whitespace or a comment) terminates a multi-line statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168
169.. _indentation:
170
171Indentation
172-----------
173
Georg Brandl57e3b682007-08-31 08:07:45 +0000174.. index:: indentation, leading whitespace, space, tab, grouping, statement grouping
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176Leading whitespace (spaces and tabs) at the beginning of a logical line is used
177to compute the indentation level of the line, which in turn is used to determine
178the grouping of statements.
179
Georg Brandl861ac1f2008-12-15 08:43:10 +0000180Tabs are replaced (from left to right) by one to eight spaces such that the
181total number of characters up to and including the replacement is a multiple of
182eight (this is intended to be the same rule as used by Unix). The total number
183of spaces preceding the first non-blank character then determines the line's
184indentation. Indentation cannot be split over multiple physical lines using
185backslashes; the whitespace up to the first backslash determines the
Georg Brandl116aa622007-08-15 14:28:22 +0000186indentation.
187
Georg Brandl861ac1f2008-12-15 08:43:10 +0000188Indentation is rejected as inconsistent if a source file mixes tabs and spaces
189in a way that makes the meaning dependent on the worth of a tab in spaces; a
190:exc:`TabError` is raised in that case.
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192**Cross-platform compatibility note:** because of the nature of text editors on
193non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
194indentation in a single source file. It should also be noted that different
195platforms may explicitly limit the maximum indentation level.
196
197A formfeed character may be present at the start of the line; it will be ignored
198for the indentation calculations above. Formfeed characters occurring elsewhere
199in the leading whitespace have an undefined effect (for instance, they may reset
200the space count to zero).
201
Georg Brandl57e3b682007-08-31 08:07:45 +0000202.. index:: INDENT token, DEDENT token
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204The indentation levels of consecutive lines are used to generate INDENT and
205DEDENT tokens, using a stack, as follows.
206
207Before the first line of the file is read, a single zero is pushed on the stack;
208this will never be popped off again. The numbers pushed on the stack will
209always be strictly increasing from bottom to top. At the beginning of each
210logical line, the line's indentation level is compared to the top of the stack.
211If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
212one INDENT token is generated. If it is smaller, it *must* be one of the
213numbers occurring on the stack; all numbers on the stack that are larger are
214popped off, and for each number popped off a DEDENT token is generated. At the
215end of the file, a DEDENT token is generated for each number remaining on the
216stack that is larger than zero.
217
218Here is an example of a correctly (though confusingly) indented piece of Python
219code::
220
221 def perm(l):
222 # Compute the list of all permutations of l
223 if len(l) <= 1:
224 return [l]
225 r = []
226 for i in range(len(l)):
227 s = l[:i] + l[i+1:]
228 p = perm(s)
229 for x in p:
230 r.append(l[i:i+1] + x)
231 return r
232
233The following example shows various indentation errors::
234
235 def perm(l): # error: first line indented
236 for i in range(len(l)): # error: not indented
237 s = l[:i] + l[i+1:]
238 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
239 for x in p:
240 r.append(l[i:i+1] + x)
241 return r # error: inconsistent dedent
242
243(Actually, the first three errors are detected by the parser; only the last
244error is found by the lexical analyzer --- the indentation of ``return r`` does
245not match a level popped off the stack.)
246
247
248.. _whitespace:
249
250Whitespace between tokens
251-------------------------
252
253Except at the beginning of a logical line or in string literals, the whitespace
254characters space, tab and formfeed can be used interchangeably to separate
255tokens. Whitespace is needed between two tokens only if their concatenation
256could otherwise be interpreted as a different token (e.g., ab is one token, but
257a b is two tokens).
258
259
260.. _other-tokens:
261
262Other tokens
263============
264
265Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
266*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
267characters (other than line terminators, discussed earlier) are not tokens, but
268serve to delimit tokens. Where ambiguity exists, a token comprises the longest
269possible string that forms a legal token, when read from left to right.
270
271
272.. _identifiers:
273
274Identifiers and keywords
275========================
276
Georg Brandl57e3b682007-08-31 08:07:45 +0000277.. index:: identifier, name
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279Identifiers (also referred to as *names*) are described by the following lexical
Georg Brandle06de8b2008-05-05 21:42:51 +0000280definitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000281
Georg Brandl57e3b682007-08-31 08:07:45 +0000282The syntax of identifiers in Python is based on the Unicode standard annex
Georg Brandle06de8b2008-05-05 21:42:51 +0000283UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for
284further details.
Georg Brandl57e3b682007-08-31 08:07:45 +0000285
286Within the ASCII range (U+0001..U+007F), the valid characters for identifiers
Georg Brandle06de8b2008-05-05 21:42:51 +0000287are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through
288``Z``, the underscore ``_`` and, except for the first character, the digits
289``0`` through ``9``.
290
291Python 3.0 introduces additional characters from outside the ASCII range (see
292:pep:`3131`). For these characters, the classification uses the version of the
293Unicode Character Database as included in the :mod:`unicodedata` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295Identifiers are unlimited in length. Case is significant.
296
Georg Brandl57e3b682007-08-31 08:07:45 +0000297.. productionlist::
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000298 identifier: `xid_start` `xid_continue`*
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000299 id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
300 id_continue: <all characters in `id_start`, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000301 xid_start: <all characters in `id_start` whose NFKC normalization is in "id_start xid_continue*">
302 xid_continue: <all characters in `id_continue` whose NFKC normalization is in "id_continue*">
Georg Brandl57e3b682007-08-31 08:07:45 +0000303
304The Unicode category codes mentioned above stand for:
305
306* *Lu* - uppercase letters
307* *Ll* - lowercase letters
308* *Lt* - titlecase letters
309* *Lm* - modifier letters
310* *Lo* - other letters
311* *Nl* - letter numbers
312* *Mn* - nonspacing marks
313* *Mc* - spacing combining marks
314* *Nd* - decimal numbers
315* *Pc* - connector punctuations
R David Murray5f16f902014-10-09 20:45:59 -0400316* *Other_ID_Start* - explicit list of characters in `PropList.txt
Benjamin Peterson7c69c1c2018-06-06 20:14:28 -0700317 <http://www.unicode.org/Public/11.0.0/ucd/PropList.txt>`_ to support backwards
R David Murray5f16f902014-10-09 20:45:59 -0400318 compatibility
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000319* *Other_ID_Continue* - likewise
Georg Brandl57e3b682007-08-31 08:07:45 +0000320
Alexander Belopolsky1a7a2e02010-12-22 01:37:36 +0000321All identifiers are converted into the normal form NFKC while parsing; comparison
322of identifiers is based on NFKC.
Georg Brandl57e3b682007-08-31 08:07:45 +0000323
324A non-normative HTML file listing all valid identifier characters for Unicode
3254.1 can be found at
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300326https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html.
Georg Brandl116aa622007-08-15 14:28:22 +0000327
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000328
Georg Brandl116aa622007-08-15 14:28:22 +0000329.. _keywords:
330
331Keywords
332--------
333
334.. index::
335 single: keyword
336 single: reserved word
337
338The following identifiers are used as reserved words, or *keywords* of the
339language, and cannot be used as ordinary identifiers. They must be spelled
Georg Brandl17761d12009-05-04 20:43:44 +0000340exactly as written here:
341
342.. sourcecode:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Tom Floyerbf9d3172017-11-08 20:31:26 +0300344 False await else import pass
345 None break except in raise
346 True class finally is return
347 and continue for lambda try
348 as def from nonlocal while
349 assert del global not with
350 async elif if or yield
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. _id-classes:
353
354Reserved classes of identifiers
355-------------------------------
356
357Certain classes of identifiers (besides keywords) have special meanings. These
358classes are identified by the patterns of leading and trailing underscore
359characters:
360
361``_*``
362 Not imported by ``from module import *``. The special identifier ``_`` is used
363 in the interactive interpreter to store the result of the last evaluation; it is
Georg Brandl1a3284e2007-12-02 09:40:06 +0000364 stored in the :mod:`builtins` module. When not in interactive mode, ``_``
Georg Brandl116aa622007-08-15 14:28:22 +0000365 has no special meaning and is not defined. See section :ref:`import`.
366
367 .. note::
368
369 The name ``_`` is often used in conjunction with internationalization;
370 refer to the documentation for the :mod:`gettext` module for more
371 information on this convention.
372
373``__*__``
Georg Brandl7d180a02010-08-02 19:32:43 +0000374 System-defined names. These names are defined by the interpreter and its
375 implementation (including the standard library). Current system names are
376 discussed in the :ref:`specialnames` section and elsewhere. More will likely
377 be defined in future versions of Python. *Any* use of ``__*__`` names, in
378 any context, that does not follow explicitly documented use, is subject to
379 breakage without warning.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381``__*``
382 Class-private names. Names in this category, when used within the context of a
383 class definition, are re-written to use a mangled form to help avoid name
384 clashes between "private" attributes of base and derived classes. See section
385 :ref:`atom-identifiers`.
386
387
388.. _literals:
389
390Literals
391========
392
Georg Brandl57e3b682007-08-31 08:07:45 +0000393.. index:: literal, constant
Georg Brandl116aa622007-08-15 14:28:22 +0000394
395Literals are notations for constant values of some built-in types.
396
397
398.. _strings:
399
Georg Brandl57e3b682007-08-31 08:07:45 +0000400String and Bytes literals
401-------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000402
Georg Brandl57e3b682007-08-31 08:07:45 +0000403.. index:: string literal, bytes literal, ASCII
Georg Brandl116aa622007-08-15 14:28:22 +0000404
405String literals are described by the following lexical definitions:
406
Georg Brandl116aa622007-08-15 14:28:22 +0000407.. productionlist::
408 stringliteral: [`stringprefix`](`shortstring` | `longstring`)
Martin Panterbc1ee462016-02-13 00:41:37 +0000409 stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
410 : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
Georg Brandl116aa622007-08-15 14:28:22 +0000411 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
Georg Brandl57e3b682007-08-31 08:07:45 +0000412 longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
413 shortstringitem: `shortstringchar` | `stringescapeseq`
414 longstringitem: `longstringchar` | `stringescapeseq`
Georg Brandl116aa622007-08-15 14:28:22 +0000415 shortstringchar: <any source character except "\" or newline or the quote>
416 longstringchar: <any source character except "\">
Georg Brandl57e3b682007-08-31 08:07:45 +0000417 stringescapeseq: "\" <any source character>
418
419.. productionlist::
420 bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`)
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100421 bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
Georg Brandl57e3b682007-08-31 08:07:45 +0000422 shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"'
423 longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""'
424 shortbytesitem: `shortbyteschar` | `bytesescapeseq`
425 longbytesitem: `longbyteschar` | `bytesescapeseq`
426 shortbyteschar: <any ASCII character except "\" or newline or the quote>
427 longbyteschar: <any ASCII character except "\">
428 bytesescapeseq: "\" <any ASCII character>
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430One syntactic restriction not indicated by these productions is that whitespace
Georg Brandl57e3b682007-08-31 08:07:45 +0000431is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the
432rest of the literal. The source character set is defined by the encoding
433declaration; it is UTF-8 if no encoding declaration is given in the source file;
434see section :ref:`encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +0000435
Georg Brandl57e3b682007-08-31 08:07:45 +0000436.. index:: triple-quoted string, Unicode Consortium, raw string
Georg Brandl116aa622007-08-15 14:28:22 +0000437
Georg Brandl57e3b682007-08-31 08:07:45 +0000438In plain English: Both types of literals can be enclosed in matching single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000439(``'``) or double quotes (``"``). They can also be enclosed in matching groups
440of three single or double quotes (these are generally referred to as
441*triple-quoted strings*). The backslash (``\``) character is used to escape
442characters that otherwise have a special meaning, such as newline, backslash
Georg Brandl57e3b682007-08-31 08:07:45 +0000443itself, or the quote character.
444
Georg Brandl57e3b682007-08-31 08:07:45 +0000445Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an
446instance of the :class:`bytes` type instead of the :class:`str` type. They
447may only contain ASCII characters; bytes with a numeric value of 128 or greater
448must be expressed with escapes.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
Georg Brandl0182f382012-06-20 11:26:03 +0200450Both string and bytes literals may optionally be prefixed with a letter ``'r'``
Benjamin Peterson162dd742010-06-29 15:57:57 +0000451or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as
452literal characters. As a result, in string literals, ``'\U'`` and ``'\u'``
Christian Heimes0b3847d2012-06-20 11:17:58 +0200453escapes in raw strings are not treated specially. Given that Python 2.x's raw
454unicode literals behave differently than Python 3.x's the ``'ur'`` syntax
455is not supported.
Benjamin Peterson162dd742010-06-29 15:57:57 +0000456
Georg Brandla4c8c472014-10-31 10:38:49 +0100457.. versionadded:: 3.3
458 The ``'rb'`` prefix of raw bytes literals has been added as a synonym
459 of ``'br'``.
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100460
Georg Brandla4c8c472014-10-31 10:38:49 +0100461.. versionadded:: 3.3
462 Support for the unicode legacy literal (``u'value'``) was reintroduced
463 to simplify the maintenance of dual Python 2.x and 3.x codebases.
464 See :pep:`414` for more information.
Armin Ronacher50364b42012-03-04 12:33:51 +0000465
Martin Panterbc1ee462016-02-13 00:41:37 +0000466A string literal with ``'f'`` or ``'F'`` in its prefix is a
467:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be
468combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw
469formatted strings are possible, but formatted bytes literals are not.
470
Georg Brandla4c8c472014-10-31 10:38:49 +0100471In triple-quoted literals, unescaped newlines and quotes are allowed (and are
472retained), except that three unescaped quotes in a row terminate the literal. (A
473"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000474
Georg Brandl57e3b682007-08-31 08:07:45 +0000475.. index:: physical line, escape sequence, Standard C, C
Georg Brandl116aa622007-08-15 14:28:22 +0000476
Georg Brandla4c8c472014-10-31 10:38:49 +0100477Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and
478bytes literals are interpreted according to rules similar to those used by
479Standard C. The recognized escape sequences are:
Georg Brandl116aa622007-08-15 14:28:22 +0000480
481+-----------------+---------------------------------+-------+
482| Escape Sequence | Meaning | Notes |
483+=================+=================================+=======+
Georg Brandl57e3b682007-08-31 08:07:45 +0000484| ``\newline`` | Backslash and newline ignored | |
Georg Brandl116aa622007-08-15 14:28:22 +0000485+-----------------+---------------------------------+-------+
486| ``\\`` | Backslash (``\``) | |
487+-----------------+---------------------------------+-------+
488| ``\'`` | Single quote (``'``) | |
489+-----------------+---------------------------------+-------+
490| ``\"`` | Double quote (``"``) | |
491+-----------------+---------------------------------+-------+
492| ``\a`` | ASCII Bell (BEL) | |
493+-----------------+---------------------------------+-------+
494| ``\b`` | ASCII Backspace (BS) | |
495+-----------------+---------------------------------+-------+
496| ``\f`` | ASCII Formfeed (FF) | |
497+-----------------+---------------------------------+-------+
498| ``\n`` | ASCII Linefeed (LF) | |
499+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000500| ``\r`` | ASCII Carriage Return (CR) | |
501+-----------------+---------------------------------+-------+
502| ``\t`` | ASCII Horizontal Tab (TAB) | |
503+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000504| ``\v`` | ASCII Vertical Tab (VT) | |
505+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000506| ``\ooo`` | Character with octal value | (1,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000507| | *ooo* | |
508+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000509| ``\xhh`` | Character with hex value *hh* | (2,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000510+-----------------+---------------------------------+-------+
511
Georg Brandl57e3b682007-08-31 08:07:45 +0000512Escape sequences only recognized in string literals are:
513
514+-----------------+---------------------------------+-------+
515| Escape Sequence | Meaning | Notes |
516+=================+=================================+=======+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300517| ``\N{name}`` | Character named *name* in the | \(4) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000518| | Unicode database | |
519+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300520| ``\uxxxx`` | Character with 16-bit hex value | \(5) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000521| | *xxxx* | |
522+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300523| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(6) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000524| | *xxxxxxxx* | |
525+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000526
527Notes:
528
529(1)
Georg Brandl57e3b682007-08-31 08:07:45 +0000530 As in Standard C, up to three octal digits are accepted.
531
532(2)
Florent Xicluna4e0f8912010-03-15 13:14:39 +0000533 Unlike in Standard C, exactly two hex digits are required.
Georg Brandl57e3b682007-08-31 08:07:45 +0000534
535(3)
536 In a bytes literal, hexadecimal and octal escapes denote the byte with the
537 given value. In a string literal, these escapes denote a Unicode character
538 with the given value.
539
540(4)
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300541 .. versionchanged:: 3.3
542 Support for name aliases [#]_ has been added.
543
544(5)
Berker Peksag4f35d792016-04-24 03:13:40 +0300545 Exactly four hex digits are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300547(6)
Ezio Melottie7f90372012-10-05 03:33:31 +0300548 Any Unicode character can be encoded this way. Exactly eight hex digits
Georg Brandle43baab2010-05-10 21:17:00 +0000549 are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000550
Georg Brandl116aa622007-08-15 14:28:22 +0000551
Georg Brandl57e3b682007-08-31 08:07:45 +0000552.. index:: unrecognized escape sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554Unlike Standard C, all unrecognized escape sequences are left in the string
Georg Brandla4c8c472014-10-31 10:38:49 +0100555unchanged, i.e., *the backslash is left in the result*. (This behavior is
Georg Brandl116aa622007-08-15 14:28:22 +0000556useful when debugging: if an escape sequence is mistyped, the resulting output
557is more easily recognized as broken.) It is also important to note that the
Georg Brandl57e3b682007-08-31 08:07:45 +0000558escape sequences only recognized in string literals fall into the category of
559unrecognized escapes for bytes literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000560
R David Murray110b6fe2016-09-08 15:34:08 -0400561 .. versionchanged:: 3.6
Serhiy Storchaka65439122018-10-19 17:42:06 +0300562 Unrecognized escape sequences produce a :exc:`DeprecationWarning`.
563
564 .. versionchanged:: 3.8
565 Unrecognized escape sequences produce a :exc:`SyntaxWarning`. In
566 some future version of Python they will be a :exc:`SyntaxError`.
R David Murray110b6fe2016-09-08 15:34:08 -0400567
Georg Brandla4c8c472014-10-31 10:38:49 +0100568Even in a raw literal, quotes can be escaped with a backslash, but the
569backslash remains in the result; for example, ``r"\""`` is a valid string
Georg Brandl57e3b682007-08-31 08:07:45 +0000570literal consisting of two characters: a backslash and a double quote; ``r"\"``
571is not a valid string literal (even a raw string cannot end in an odd number of
Georg Brandla4c8c472014-10-31 10:38:49 +0100572backslashes). Specifically, *a raw literal cannot end in a single backslash*
Georg Brandl57e3b682007-08-31 08:07:45 +0000573(since the backslash would escape the following quote character). Note also
574that a single backslash followed by a newline is interpreted as those two
Georg Brandla4c8c472014-10-31 10:38:49 +0100575characters as part of the literal, *not* as a line continuation.
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577
İsmail Arılık3764bb02018-01-12 09:18:54 +0300578.. _string-concatenation:
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580String literal concatenation
581----------------------------
582
Benjamin Peterson162dd742010-06-29 15:57:57 +0000583Multiple adjacent string or bytes literals (delimited by whitespace), possibly
584using different quoting conventions, are allowed, and their meaning is the same
585as their concatenation. Thus, ``"hello" 'world'`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +0000586``"helloworld"``. This feature can be used to reduce the number of backslashes
587needed, to split long strings conveniently across long lines, or even to add
588comments to parts of strings, for example::
589
590 re.compile("[A-Za-z_]" # letter or underscore
591 "[A-Za-z0-9_]*" # letter, digit or underscore
592 )
593
594Note that this feature is defined at the syntactical level, but implemented at
595compile time. The '+' operator must be used to concatenate string expressions
596at run time. Also note that literal concatenation can use different quoting
Martin Panterbc1ee462016-02-13 00:41:37 +0000597styles for each component (even mixing raw strings and triple quoted strings),
598and formatted string literals may be concatenated with plain string literals.
599
600
601.. index::
602 single: formatted string literal
603 single: interpolated string literal
604 single: string; formatted literal
605 single: string; interpolated literal
606 single: f-string
607.. _f-strings:
608
609Formatted string literals
610-------------------------
611
612.. versionadded:: 3.6
613
614A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
615that is prefixed with ``'f'`` or ``'F'``. These strings may contain
616replacement fields, which are expressions delimited by curly braces ``{}``.
617While other string literals always have a constant value, formatted strings
618are really expressions evaluated at run time.
619
620Escape sequences are decoded like in ordinary string literals (except when
621a literal is also marked as a raw string). After decoding, the grammar
622for the contents of the string is:
623
624.. productionlist::
625 f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
626 replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}"
Martin Pantered74e242016-06-12 01:56:24 +0000627 f_expression: (`conditional_expression` | "*" `or_expr`)
628 : ("," `conditional_expression` | "," "*" `or_expr`)* [","]
Martin Panterbc1ee462016-02-13 00:41:37 +0000629 : | `yield_expression`
630 conversion: "s" | "r" | "a"
631 format_spec: (`literal_char` | NULL | `replacement_field`)*
632 literal_char: <any code point except "{", "}" or NULL>
633
634The parts of the string outside curly braces are treated literally,
635except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
636with the corresponding single curly brace. A single opening curly
637bracket ``'{'`` marks a replacement field, which starts with a
638Python expression. After the expression, there may be a conversion field,
639introduced by an exclamation point ``'!'``. A format specifier may also
640be appended, introduced by a colon ``':'``. A replacement field ends
641with a closing curly bracket ``'}'``.
642
643Expressions in formatted string literals are treated like regular
644Python expressions surrounded by parentheses, with a few exceptions.
645An empty expression is not allowed, and a :keyword:`lambda` expression
646must be surrounded by explicit parentheses. Replacement expressions
647can contain line breaks (e.g. in triple-quoted strings), but they
648cannot contain comments. Each expression is evaluated in the context
649where the formatted string literal appears, in order from left to right.
650
651If a conversion is specified, the result of evaluating the expression
652is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
653the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
654
655The result is then formatted using the :func:`format` protocol. The
656format specifier is passed to the :meth:`__format__` method of the
657expression or conversion result. An empty string is passed when the
658format specifier is omitted. The formatted result is then included in
659the final value of the whole string.
660
KatherineMichelf4e21a22017-12-19 15:03:09 -0600661Top-level format specifiers may include nested replacement fields. These nested
662fields may include their own conversion fields and :ref:`format specifiers
663<formatspec>`, but may not include more deeply-nested replacement fields. The
664:ref:`format specifier mini-language <formatspec>` is the same as that used by
665the string .format() method.
Martin Panterbc1ee462016-02-13 00:41:37 +0000666
667Formatted string literals may be concatenated, but replacement fields
668cannot be split across literals.
669
670Some examples of formatted string literals::
671
672 >>> name = "Fred"
673 >>> f"He said his name is {name!r}."
674 "He said his name is 'Fred'."
675 >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
676 "He said his name is 'Fred'."
677 >>> width = 10
678 >>> precision = 4
679 >>> value = decimal.Decimal("12.34567")
680 >>> f"result: {value:{width}.{precision}}" # nested fields
681 'result: 12.35'
Mariattaf3618972017-09-16 11:46:43 -0700682 >>> today = datetime(year=2017, month=1, day=27)
Cheryl Sabellab2993932018-01-31 16:37:51 -0500683 >>> f"{today:%B %d, %Y}" # using date format specifier
Mariattaf3618972017-09-16 11:46:43 -0700684 'January 27, 2017'
685 >>> number = 1024
Mariatta63c591c2017-09-17 07:43:31 -0700686 >>> f"{number:#0x}" # using integer format specifier
Mariattaf3618972017-09-16 11:46:43 -0700687 '0x400'
Martin Panterbc1ee462016-02-13 00:41:37 +0000688
689A consequence of sharing the same syntax as regular string literals is
690that characters in the replacement fields must not conflict with the
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500691quoting used in the outer formatted string literal::
Martin Panterbc1ee462016-02-13 00:41:37 +0000692
693 f"abc {a["x"]} def" # error: outer string literal ended prematurely
Martin Panterbc1ee462016-02-13 00:41:37 +0000694 f"abc {a['x']} def" # workaround: use different quoting
695
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500696Backslashes are not allowed in format expressions and will raise
697an error::
698
699 f"newline: {ord('\n')}" # raises SyntaxError
700
701To include a value in which a backslash escape is required, create
702a temporary variable.
703
704 >>> newline = ord('\n')
705 >>> f"newline: {newline}"
706 'newline: 10'
Martin Panterbc1ee462016-02-13 00:41:37 +0000707
Mariattad4e89282017-03-10 08:58:40 -0800708Formatted string literals cannot be used as docstrings, even if they do not
709include expressions.
710
711::
712
713 >>> def foo():
714 ... f"Not a docstring"
715 ...
716 >>> foo.__doc__ is None
717 True
718
Martin Panterbc1ee462016-02-13 00:41:37 +0000719See also :pep:`498` for the proposal that added formatted string literals,
720and :meth:`str.format`, which uses a related format string mechanism.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722
723.. _numbers:
724
725Numeric literals
726----------------
727
Georg Brandlba956ae2007-11-29 17:24:34 +0000728.. index:: number, numeric literal, integer literal
729 floating point literal, hexadecimal literal
Georg Brandl57e3b682007-08-31 08:07:45 +0000730 octal literal, binary literal, decimal literal, imaginary literal, complex literal
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Georg Brandl95817b32008-05-11 14:30:18 +0000732There are three types of numeric literals: integers, floating point numbers, and
733imaginary numbers. There are no complex literals (complex numbers can be formed
734by adding a real number and an imaginary number).
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736Note that numeric literals do not include a sign; a phrase like ``-1`` is
737actually an expression composed of the unary operator '``-``' and the literal
738``1``.
739
740
741.. _integers:
742
743Integer literals
744----------------
745
746Integer literals are described by the following lexical definitions:
747
748.. productionlist::
Brett Cannona721aba2016-09-09 14:57:09 -0700749 integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger`
750 decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")*
751 bininteger: "0" ("b" | "B") (["_"] `bindigit`)+
752 octinteger: "0" ("o" | "O") (["_"] `octdigit`)+
753 hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+
Georg Brandl57e3b682007-08-31 08:07:45 +0000754 nonzerodigit: "1"..."9"
755 digit: "0"..."9"
Brett Cannona721aba2016-09-09 14:57:09 -0700756 bindigit: "0" | "1"
Georg Brandl116aa622007-08-15 14:28:22 +0000757 octdigit: "0"..."7"
758 hexdigit: `digit` | "a"..."f" | "A"..."F"
Georg Brandl116aa622007-08-15 14:28:22 +0000759
Georg Brandl57e3b682007-08-31 08:07:45 +0000760There is no limit for the length of integer literals apart from what can be
761stored in available memory.
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Brett Cannona721aba2016-09-09 14:57:09 -0700763Underscores are ignored for determining the numeric value of the literal. They
764can be used to group digits for enhanced readability. One underscore can occur
765between digits, and after base specifiers like ``0x``.
766
Georg Brandl116aa622007-08-15 14:28:22 +0000767Note that leading zeros in a non-zero decimal number are not allowed. This is
768for disambiguation with C-style octal literals, which Python used before version
7693.0.
770
771Some examples of integer literals::
772
773 7 2147483647 0o177 0b100110111
Raymond Hettinger9ecf9e22015-05-22 16:37:49 -0700774 3 79228162514264337593543950336 0o377 0xdeadbeef
Brett Cannona721aba2016-09-09 14:57:09 -0700775 100_000_000_000 0b_1110_0101
776
777.. versionchanged:: 3.6
778 Underscores are now allowed for grouping purposes in literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000779
780
781.. _floating:
782
783Floating point literals
784-----------------------
785
786Floating point literals are described by the following lexical definitions:
787
788.. productionlist::
789 floatnumber: `pointfloat` | `exponentfloat`
Brett Cannona721aba2016-09-09 14:57:09 -0700790 pointfloat: [`digitpart`] `fraction` | `digitpart` "."
791 exponentfloat: (`digitpart` | `pointfloat`) `exponent`
792 digitpart: `digit` (["_"] `digit`)*
793 fraction: "." `digitpart`
794 exponent: ("e" | "E") ["+" | "-"] `digitpart`
Georg Brandl116aa622007-08-15 14:28:22 +0000795
796Note that the integer and exponent parts are always interpreted using radix 10.
797For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The
Brett Cannona721aba2016-09-09 14:57:09 -0700798allowed range of floating point literals is implementation-dependent. As in
799integer literals, underscores are supported for digit grouping.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Brett Cannona721aba2016-09-09 14:57:09 -0700801Some examples of floating point literals::
802
803 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
Georg Brandl116aa622007-08-15 14:28:22 +0000804
Brett Cannona721aba2016-09-09 14:57:09 -0700805.. versionchanged:: 3.6
806 Underscores are now allowed for grouping purposes in literals.
807
Georg Brandl116aa622007-08-15 14:28:22 +0000808
809.. _imaginary:
810
811Imaginary literals
812------------------
813
814Imaginary literals are described by the following lexical definitions:
815
816.. productionlist::
Brett Cannona721aba2016-09-09 14:57:09 -0700817 imagnumber: (`floatnumber` | `digitpart`) ("j" | "J")
Georg Brandl116aa622007-08-15 14:28:22 +0000818
819An imaginary literal yields a complex number with a real part of 0.0. Complex
820numbers are represented as a pair of floating point numbers and have the same
821restrictions on their range. To create a complex number with a nonzero real
822part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
823imaginary literals::
824
Brett Cannona721aba2016-09-09 14:57:09 -0700825 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827
828.. _operators:
829
830Operators
831=========
832
833.. index:: single: operators
834
Martin Panter1050d2d2016-07-26 11:18:21 +0200835The following tokens are operators:
836
837.. code-block:: none
838
Georg Brandl116aa622007-08-15 14:28:22 +0000839
Benjamin Petersonbd592412014-08-06 22:50:30 -0700840 + - * ** / // % @
Georg Brandl116aa622007-08-15 14:28:22 +0000841 << >> & | ^ ~
842 < > <= >= == !=
843
844
845.. _delimiters:
846
847Delimiters
848==========
849
850.. index:: single: delimiters
851
Martin Panter1050d2d2016-07-26 11:18:21 +0200852The following tokens serve as delimiters in the grammar:
853
854.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Georg Brandl0df79792008-10-04 18:33:26 +0000856 ( ) [ ] { }
Georg Brandl97f96232013-10-08 21:28:22 +0200857 , : . ; @ = ->
Benjamin Petersonbd592412014-08-06 22:50:30 -0700858 += -= *= /= //= %= @=
Georg Brandl116aa622007-08-15 14:28:22 +0000859 &= |= ^= >>= <<= **=
860
861The period can also occur in floating-point and imaginary literals. A sequence
Georg Brandl57e3b682007-08-31 08:07:45 +0000862of three periods has a special meaning as an ellipsis literal. The second half
Georg Brandl116aa622007-08-15 14:28:22 +0000863of the list, the augmented assignment operators, serve lexically as delimiters,
864but also perform an operation.
865
866The following printing ASCII characters have special meaning as part of other
Martin Panter1050d2d2016-07-26 11:18:21 +0200867tokens or are otherwise significant to the lexical analyzer:
868
869.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871 ' " # \
872
Georg Brandl116aa622007-08-15 14:28:22 +0000873The following printing ASCII characters are not used in Python. Their
Martin Panter1050d2d2016-07-26 11:18:21 +0200874occurrence outside string literals and comments is an unconditional error:
875
876.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Georg Brandle43baab2010-05-10 21:17:00 +0000878 $ ? `
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300879
880
881.. rubric:: Footnotes
882
Benjamin Peterson7c69c1c2018-06-06 20:14:28 -0700883.. [#] http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt