blob: 4b49738e268f49b4763745028c66c88c4900d851 [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
50sequence. In source files, any of the standard platform line termination
51sequences can be used - the Unix form using ASCII LF (linefeed), the Windows
Georg Brandlc575c902008-09-13 17:46:05 +000052form using the ASCII sequence CR LF (return followed by linefeed), or the old
Georg Brandl116aa622007-08-15 14:28:22 +000053Macintosh form using the ASCII CR (return) character. All of these forms can be
54used equally, regardless of platform.
55
56When embedding Python, source code strings should be passed to Python APIs using
57the standard C conventions for newline characters (the ``\n`` character,
58representing ASCII LF, is the line terminator).
59
60
61.. _comments:
62
63Comments
64--------
65
Georg Brandl57e3b682007-08-31 08:07:45 +000066.. index:: comment, hash character
Georg Brandl116aa622007-08-15 14:28:22 +000067
68A comment starts with a hash character (``#``) that is not part of a string
69literal, and ends at the end of the physical line. A comment signifies the end
70of the logical line unless the implicit line joining rules are invoked. Comments
71are ignored by the syntax; they are not tokens.
72
73
74.. _encodings:
75
76Encoding declarations
77---------------------
78
Georg Brandl57e3b682007-08-31 08:07:45 +000079.. index:: source character set, encodings
Georg Brandl116aa622007-08-15 14:28:22 +000080
81If a comment in the first or second line of the Python script matches the
82regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
83encoding declaration; the first group of this expression names the encoding of
84the source code file. The recommended forms of this expression are ::
85
86 # -*- coding: <encoding-name> -*-
87
88which is recognized also by GNU Emacs, and ::
89
90 # vim:fileencoding=<encoding-name>
91
Georg Brandl57e3b682007-08-31 08:07:45 +000092which is recognized by Bram Moolenaar's VIM.
93
94If no encoding declaration is found, the default encoding is UTF-8. In
95addition, if the first bytes of the file are the UTF-8 byte-order mark
96(``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported,
97among others, by Microsoft's :program:`notepad`).
Georg Brandl116aa622007-08-15 14:28:22 +000098
99If an encoding is declared, the encoding name must be recognized by Python. The
Georg Brandl57e3b682007-08-31 08:07:45 +0000100encoding is used for all lexical analysis, including string literals, comments
101and identifiers. The encoding declaration must appear on a line of its own.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000103.. XXX there should be a list of supported encodings.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105
106.. _explicit-joining:
107
108Explicit line joining
109---------------------
110
Georg Brandl57e3b682007-08-31 08:07:45 +0000111.. index:: physical line, line joining, line continuation, backslash character
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113Two or more physical lines may be joined into logical lines using backslash
114characters (``\``), as follows: when a physical line ends in a backslash that is
115not part of a string literal or comment, it is joined with the following forming
116a single logical line, deleting the backslash and the following end-of-line
Georg Brandl57e3b682007-08-31 08:07:45 +0000117character. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119 if 1900 < year < 2100 and 1 <= month <= 12 \
120 and 1 <= day <= 31 and 0 <= hour < 24 \
121 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
122 return 1
123
124A line ending in a backslash cannot carry a comment. A backslash does not
125continue a comment. A backslash does not continue a token except for string
126literals (i.e., tokens other than string literals cannot be split across
127physical lines using a backslash). A backslash is illegal elsewhere on a line
128outside a string literal.
129
130
131.. _implicit-joining:
132
133Implicit line joining
134---------------------
135
136Expressions in parentheses, square brackets or curly braces can be split over
137more than one physical line without using backslashes. For example::
138
139 month_names = ['Januari', 'Februari', 'Maart', # These are the
140 'April', 'Mei', 'Juni', # Dutch names
141 'Juli', 'Augustus', 'September', # for the months
142 'Oktober', 'November', 'December'] # of the year
143
144Implicitly continued lines can carry comments. The indentation of the
145continuation lines is not important. Blank continuation lines are allowed.
146There is no NEWLINE token between implicit continuation lines. Implicitly
147continued lines can also occur within triple-quoted strings (see below); in that
148case they cannot carry comments.
149
150
151.. _blank-lines:
152
153Blank lines
154-----------
155
156.. index:: single: blank line
157
158A logical line that contains only spaces, tabs, formfeeds and possibly a
159comment, is ignored (i.e., no NEWLINE token is generated). During interactive
160input of statements, handling of a blank line may differ depending on the
Georg Brandl57e3b682007-08-31 08:07:45 +0000161implementation of the read-eval-print loop. In the standard interactive
162interpreter, an entirely blank logical line (i.e. one containing not even
163whitespace or a comment) terminates a multi-line statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165
166.. _indentation:
167
168Indentation
169-----------
170
Georg Brandl57e3b682007-08-31 08:07:45 +0000171.. index:: indentation, leading whitespace, space, tab, grouping, statement grouping
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173Leading whitespace (spaces and tabs) at the beginning of a logical line is used
174to compute the indentation level of the line, which in turn is used to determine
175the grouping of statements.
176
Georg Brandl861ac1f2008-12-15 08:43:10 +0000177Tabs are replaced (from left to right) by one to eight spaces such that the
178total number of characters up to and including the replacement is a multiple of
179eight (this is intended to be the same rule as used by Unix). The total number
180of spaces preceding the first non-blank character then determines the line's
181indentation. Indentation cannot be split over multiple physical lines using
182backslashes; the whitespace up to the first backslash determines the
Georg Brandl116aa622007-08-15 14:28:22 +0000183indentation.
184
Georg Brandl861ac1f2008-12-15 08:43:10 +0000185Indentation is rejected as inconsistent if a source file mixes tabs and spaces
186in a way that makes the meaning dependent on the worth of a tab in spaces; a
187:exc:`TabError` is raised in that case.
188
Georg Brandl116aa622007-08-15 14:28:22 +0000189**Cross-platform compatibility note:** because of the nature of text editors on
190non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
191indentation in a single source file. It should also be noted that different
192platforms may explicitly limit the maximum indentation level.
193
194A formfeed character may be present at the start of the line; it will be ignored
195for the indentation calculations above. Formfeed characters occurring elsewhere
196in the leading whitespace have an undefined effect (for instance, they may reset
197the space count to zero).
198
Georg Brandl57e3b682007-08-31 08:07:45 +0000199.. index:: INDENT token, DEDENT token
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201The indentation levels of consecutive lines are used to generate INDENT and
202DEDENT tokens, using a stack, as follows.
203
204Before the first line of the file is read, a single zero is pushed on the stack;
205this will never be popped off again. The numbers pushed on the stack will
206always be strictly increasing from bottom to top. At the beginning of each
207logical line, the line's indentation level is compared to the top of the stack.
208If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
209one INDENT token is generated. If it is smaller, it *must* be one of the
210numbers occurring on the stack; all numbers on the stack that are larger are
211popped off, and for each number popped off a DEDENT token is generated. At the
212end of the file, a DEDENT token is generated for each number remaining on the
213stack that is larger than zero.
214
215Here is an example of a correctly (though confusingly) indented piece of Python
216code::
217
218 def perm(l):
219 # Compute the list of all permutations of l
220 if len(l) <= 1:
221 return [l]
222 r = []
223 for i in range(len(l)):
224 s = l[:i] + l[i+1:]
225 p = perm(s)
226 for x in p:
227 r.append(l[i:i+1] + x)
228 return r
229
230The following example shows various indentation errors::
231
232 def perm(l): # error: first line indented
233 for i in range(len(l)): # error: not indented
234 s = l[:i] + l[i+1:]
235 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
236 for x in p:
237 r.append(l[i:i+1] + x)
238 return r # error: inconsistent dedent
239
240(Actually, the first three errors are detected by the parser; only the last
241error is found by the lexical analyzer --- the indentation of ``return r`` does
242not match a level popped off the stack.)
243
244
245.. _whitespace:
246
247Whitespace between tokens
248-------------------------
249
250Except at the beginning of a logical line or in string literals, the whitespace
251characters space, tab and formfeed can be used interchangeably to separate
252tokens. Whitespace is needed between two tokens only if their concatenation
253could otherwise be interpreted as a different token (e.g., ab is one token, but
254a b is two tokens).
255
256
257.. _other-tokens:
258
259Other tokens
260============
261
262Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
263*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
264characters (other than line terminators, discussed earlier) are not tokens, but
265serve to delimit tokens. Where ambiguity exists, a token comprises the longest
266possible string that forms a legal token, when read from left to right.
267
268
269.. _identifiers:
270
271Identifiers and keywords
272========================
273
Georg Brandl57e3b682007-08-31 08:07:45 +0000274.. index:: identifier, name
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276Identifiers (also referred to as *names*) are described by the following lexical
Georg Brandle06de8b2008-05-05 21:42:51 +0000277definitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
Georg Brandl57e3b682007-08-31 08:07:45 +0000279The syntax of identifiers in Python is based on the Unicode standard annex
Georg Brandle06de8b2008-05-05 21:42:51 +0000280UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for
281further details.
Georg Brandl57e3b682007-08-31 08:07:45 +0000282
283Within the ASCII range (U+0001..U+007F), the valid characters for identifiers
Georg Brandle06de8b2008-05-05 21:42:51 +0000284are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through
285``Z``, the underscore ``_`` and, except for the first character, the digits
286``0`` through ``9``.
287
288Python 3.0 introduces additional characters from outside the ASCII range (see
289:pep:`3131`). For these characters, the classification uses the version of the
290Unicode Character Database as included in the :mod:`unicodedata` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292Identifiers are unlimited in length. Case is significant.
293
Georg Brandl57e3b682007-08-31 08:07:45 +0000294.. productionlist::
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000295 identifier: `xid_start` `xid_continue`*
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000296 id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
297 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 +0000298 xid_start: <all characters in `id_start` whose NFKC normalization is in "id_start xid_continue*">
299 xid_continue: <all characters in `id_continue` whose NFKC normalization is in "id_continue*">
Georg Brandl57e3b682007-08-31 08:07:45 +0000300
301The Unicode category codes mentioned above stand for:
302
303* *Lu* - uppercase letters
304* *Ll* - lowercase letters
305* *Lt* - titlecase letters
306* *Lm* - modifier letters
307* *Lo* - other letters
308* *Nl* - letter numbers
309* *Mn* - nonspacing marks
310* *Mc* - spacing combining marks
311* *Nd* - decimal numbers
312* *Pc* - connector punctuations
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000313* *Other_ID_Start* - explicit list of characters in `PropList.txt <http://unicode.org/Public/UNIDATA/PropList.txt>`_ to support backwards compatibility
314* *Other_ID_Continue* - likewise
Georg Brandl57e3b682007-08-31 08:07:45 +0000315
Alexander Belopolsky1a7a2e02010-12-22 01:37:36 +0000316All identifiers are converted into the normal form NFKC while parsing; comparison
317of identifiers is based on NFKC.
Georg Brandl57e3b682007-08-31 08:07:45 +0000318
319A non-normative HTML file listing all valid identifier characters for Unicode
3204.1 can be found at
321http://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000323
Georg Brandl116aa622007-08-15 14:28:22 +0000324.. _keywords:
325
326Keywords
327--------
328
329.. index::
330 single: keyword
331 single: reserved word
332
333The following identifiers are used as reserved words, or *keywords* of the
334language, and cannot be used as ordinary identifiers. They must be spelled
Georg Brandl17761d12009-05-04 20:43:44 +0000335exactly as written here:
336
337.. sourcecode:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Georg Brandl57e3b682007-08-31 08:07:45 +0000339 False class finally is return
340 None continue for lambda try
341 True def from nonlocal while
342 and del global not with
343 as elif if or yield
344 assert else import pass
345 break except in raise
Georg Brandl116aa622007-08-15 14:28:22 +0000346
347.. _id-classes:
348
349Reserved classes of identifiers
350-------------------------------
351
352Certain classes of identifiers (besides keywords) have special meanings. These
353classes are identified by the patterns of leading and trailing underscore
354characters:
355
356``_*``
357 Not imported by ``from module import *``. The special identifier ``_`` is used
358 in the interactive interpreter to store the result of the last evaluation; it is
Georg Brandl1a3284e2007-12-02 09:40:06 +0000359 stored in the :mod:`builtins` module. When not in interactive mode, ``_``
Georg Brandl116aa622007-08-15 14:28:22 +0000360 has no special meaning and is not defined. See section :ref:`import`.
361
362 .. note::
363
364 The name ``_`` is often used in conjunction with internationalization;
365 refer to the documentation for the :mod:`gettext` module for more
366 information on this convention.
367
368``__*__``
Georg Brandl7d180a02010-08-02 19:32:43 +0000369 System-defined names. These names are defined by the interpreter and its
370 implementation (including the standard library). Current system names are
371 discussed in the :ref:`specialnames` section and elsewhere. More will likely
372 be defined in future versions of Python. *Any* use of ``__*__`` names, in
373 any context, that does not follow explicitly documented use, is subject to
374 breakage without warning.
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376``__*``
377 Class-private names. Names in this category, when used within the context of a
378 class definition, are re-written to use a mangled form to help avoid name
379 clashes between "private" attributes of base and derived classes. See section
380 :ref:`atom-identifiers`.
381
382
383.. _literals:
384
385Literals
386========
387
Georg Brandl57e3b682007-08-31 08:07:45 +0000388.. index:: literal, constant
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390Literals are notations for constant values of some built-in types.
391
392
393.. _strings:
394
Georg Brandl57e3b682007-08-31 08:07:45 +0000395String and Bytes literals
396-------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000397
Georg Brandl57e3b682007-08-31 08:07:45 +0000398.. index:: string literal, bytes literal, ASCII
Georg Brandl116aa622007-08-15 14:28:22 +0000399
400String literals are described by the following lexical definitions:
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402.. productionlist::
403 stringliteral: [`stringprefix`](`shortstring` | `longstring`)
Georg Brandl57e3b682007-08-31 08:07:45 +0000404 stringprefix: "r" | "R"
Georg Brandl116aa622007-08-15 14:28:22 +0000405 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
Georg Brandl57e3b682007-08-31 08:07:45 +0000406 longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
407 shortstringitem: `shortstringchar` | `stringescapeseq`
408 longstringitem: `longstringchar` | `stringescapeseq`
Georg Brandl116aa622007-08-15 14:28:22 +0000409 shortstringchar: <any source character except "\" or newline or the quote>
410 longstringchar: <any source character except "\">
Georg Brandl57e3b682007-08-31 08:07:45 +0000411 stringescapeseq: "\" <any source character>
412
413.. productionlist::
414 bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`)
Benjamin Peterson162dd742010-06-29 15:57:57 +0000415 bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR"
Georg Brandl57e3b682007-08-31 08:07:45 +0000416 shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"'
417 longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""'
418 shortbytesitem: `shortbyteschar` | `bytesescapeseq`
419 longbytesitem: `longbyteschar` | `bytesescapeseq`
420 shortbyteschar: <any ASCII character except "\" or newline or the quote>
421 longbyteschar: <any ASCII character except "\">
422 bytesescapeseq: "\" <any ASCII character>
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424One syntactic restriction not indicated by these productions is that whitespace
Georg Brandl57e3b682007-08-31 08:07:45 +0000425is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the
426rest of the literal. The source character set is defined by the encoding
427declaration; it is UTF-8 if no encoding declaration is given in the source file;
428see section :ref:`encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
Georg Brandl57e3b682007-08-31 08:07:45 +0000430.. index:: triple-quoted string, Unicode Consortium, raw string
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Georg Brandl57e3b682007-08-31 08:07:45 +0000432In plain English: Both types of literals can be enclosed in matching single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000433(``'``) or double quotes (``"``). They can also be enclosed in matching groups
434of three single or double quotes (these are generally referred to as
435*triple-quoted strings*). The backslash (``\``) character is used to escape
436characters that otherwise have a special meaning, such as newline, backslash
Georg Brandl57e3b682007-08-31 08:07:45 +0000437itself, or the quote character.
438
Georg Brandl57e3b682007-08-31 08:07:45 +0000439Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an
440instance of the :class:`bytes` type instead of the :class:`str` type. They
441may only contain ASCII characters; bytes with a numeric value of 128 or greater
442must be expressed with escapes.
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Benjamin Peterson162dd742010-06-29 15:57:57 +0000444Both string and bytes literals may optionally be prefixed with a letter ``'r'``
445or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as
446literal characters. As a result, in string literals, ``'\U'`` and ``'\u'``
447escapes in raw strings are not treated specially.
448
Georg Brandl116aa622007-08-15 14:28:22 +0000449In triple-quoted strings, unescaped newlines and quotes are allowed (and are
450retained), except that three unescaped quotes in a row terminate the string. (A
451"quote" is the character used to open the string, i.e. either ``'`` or ``"``.)
452
Georg Brandl57e3b682007-08-31 08:07:45 +0000453.. index:: physical line, escape sequence, Standard C, C
Georg Brandl116aa622007-08-15 14:28:22 +0000454
455Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in strings are
456interpreted according to rules similar to those used by Standard C. The
457recognized escape sequences are:
458
459+-----------------+---------------------------------+-------+
460| Escape Sequence | Meaning | Notes |
461+=================+=================================+=======+
Georg Brandl57e3b682007-08-31 08:07:45 +0000462| ``\newline`` | Backslash and newline ignored | |
Georg Brandl116aa622007-08-15 14:28:22 +0000463+-----------------+---------------------------------+-------+
464| ``\\`` | Backslash (``\``) | |
465+-----------------+---------------------------------+-------+
466| ``\'`` | Single quote (``'``) | |
467+-----------------+---------------------------------+-------+
468| ``\"`` | Double quote (``"``) | |
469+-----------------+---------------------------------+-------+
470| ``\a`` | ASCII Bell (BEL) | |
471+-----------------+---------------------------------+-------+
472| ``\b`` | ASCII Backspace (BS) | |
473+-----------------+---------------------------------+-------+
474| ``\f`` | ASCII Formfeed (FF) | |
475+-----------------+---------------------------------+-------+
476| ``\n`` | ASCII Linefeed (LF) | |
477+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000478| ``\r`` | ASCII Carriage Return (CR) | |
479+-----------------+---------------------------------+-------+
480| ``\t`` | ASCII Horizontal Tab (TAB) | |
481+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000482| ``\v`` | ASCII Vertical Tab (VT) | |
483+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000484| ``\ooo`` | Character with octal value | (1,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000485| | *ooo* | |
486+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000487| ``\xhh`` | Character with hex value *hh* | (2,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000488+-----------------+---------------------------------+-------+
489
Georg Brandl57e3b682007-08-31 08:07:45 +0000490Escape sequences only recognized in string literals are:
491
492+-----------------+---------------------------------+-------+
493| Escape Sequence | Meaning | Notes |
494+=================+=================================+=======+
495| ``\N{name}`` | Character named *name* in the | |
496| | Unicode database | |
497+-----------------+---------------------------------+-------+
498| ``\uxxxx`` | Character with 16-bit hex value | \(4) |
499| | *xxxx* | |
500+-----------------+---------------------------------+-------+
501| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(5) |
502| | *xxxxxxxx* | |
503+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505Notes:
506
507(1)
Georg Brandl57e3b682007-08-31 08:07:45 +0000508 As in Standard C, up to three octal digits are accepted.
509
510(2)
Florent Xicluna4e0f8912010-03-15 13:14:39 +0000511 Unlike in Standard C, exactly two hex digits are required.
Georg Brandl57e3b682007-08-31 08:07:45 +0000512
513(3)
514 In a bytes literal, hexadecimal and octal escapes denote the byte with the
515 given value. In a string literal, these escapes denote a Unicode character
516 with the given value.
517
518(4)
Georg Brandl116aa622007-08-15 14:28:22 +0000519 Individual code units which form parts of a surrogate pair can be encoded using
Georg Brandle43baab2010-05-10 21:17:00 +0000520 this escape sequence. Exactly four hex digits are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Georg Brandl57e3b682007-08-31 08:07:45 +0000522(5)
Georg Brandl116aa622007-08-15 14:28:22 +0000523 Any Unicode character can be encoded this way, but characters outside the Basic
524 Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is
Georg Brandle43baab2010-05-10 21:17:00 +0000525 compiled to use 16-bit code units (the default). Exactly eight hex digits
526 are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000527
Georg Brandl116aa622007-08-15 14:28:22 +0000528
Georg Brandl57e3b682007-08-31 08:07:45 +0000529.. index:: unrecognized escape sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531Unlike Standard C, all unrecognized escape sequences are left in the string
532unchanged, i.e., *the backslash is left in the string*. (This behavior is
533useful when debugging: if an escape sequence is mistyped, the resulting output
534is more easily recognized as broken.) It is also important to note that the
Georg Brandl57e3b682007-08-31 08:07:45 +0000535escape sequences only recognized in string literals fall into the category of
536unrecognized escapes for bytes literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Georg Brandl57e3b682007-08-31 08:07:45 +0000538Even in a raw string, string quotes can be escaped with a backslash, but the
539backslash remains in the string; for example, ``r"\""`` is a valid string
540literal consisting of two characters: a backslash and a double quote; ``r"\"``
541is not a valid string literal (even a raw string cannot end in an odd number of
542backslashes). Specifically, *a raw string cannot end in a single backslash*
543(since the backslash would escape the following quote character). Note also
544that a single backslash followed by a newline is interpreted as those two
545characters as part of the string, *not* as a line continuation.
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547
548.. _string-catenation:
549
550String literal concatenation
551----------------------------
552
Benjamin Peterson162dd742010-06-29 15:57:57 +0000553Multiple adjacent string or bytes literals (delimited by whitespace), possibly
554using different quoting conventions, are allowed, and their meaning is the same
555as their concatenation. Thus, ``"hello" 'world'`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +0000556``"helloworld"``. This feature can be used to reduce the number of backslashes
557needed, to split long strings conveniently across long lines, or even to add
558comments to parts of strings, for example::
559
560 re.compile("[A-Za-z_]" # letter or underscore
561 "[A-Za-z0-9_]*" # letter, digit or underscore
562 )
563
564Note that this feature is defined at the syntactical level, but implemented at
565compile time. The '+' operator must be used to concatenate string expressions
566at run time. Also note that literal concatenation can use different quoting
567styles for each component (even mixing raw strings and triple quoted strings).
568
569
570.. _numbers:
571
572Numeric literals
573----------------
574
Georg Brandlba956ae2007-11-29 17:24:34 +0000575.. index:: number, numeric literal, integer literal
576 floating point literal, hexadecimal literal
Georg Brandl57e3b682007-08-31 08:07:45 +0000577 octal literal, binary literal, decimal literal, imaginary literal, complex literal
Georg Brandl116aa622007-08-15 14:28:22 +0000578
Georg Brandl95817b32008-05-11 14:30:18 +0000579There are three types of numeric literals: integers, floating point numbers, and
580imaginary numbers. There are no complex literals (complex numbers can be formed
581by adding a real number and an imaginary number).
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583Note that numeric literals do not include a sign; a phrase like ``-1`` is
584actually an expression composed of the unary operator '``-``' and the literal
585``1``.
586
587
588.. _integers:
589
590Integer literals
591----------------
592
593Integer literals are described by the following lexical definitions:
594
595.. productionlist::
Georg Brandlddee3082008-04-09 18:46:46 +0000596 integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger`
Georg Brandl116aa622007-08-15 14:28:22 +0000597 decimalinteger: `nonzerodigit` `digit`* | "0"+
Georg Brandl57e3b682007-08-31 08:07:45 +0000598 nonzerodigit: "1"..."9"
599 digit: "0"..."9"
Georg Brandl116aa622007-08-15 14:28:22 +0000600 octinteger: "0" ("o" | "O") `octdigit`+
601 hexinteger: "0" ("x" | "X") `hexdigit`+
602 bininteger: "0" ("b" | "B") `bindigit`+
Georg Brandl116aa622007-08-15 14:28:22 +0000603 octdigit: "0"..."7"
604 hexdigit: `digit` | "a"..."f" | "A"..."F"
Georg Brandl57e3b682007-08-31 08:07:45 +0000605 bindigit: "0" | "1"
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Georg Brandl57e3b682007-08-31 08:07:45 +0000607There is no limit for the length of integer literals apart from what can be
608stored in available memory.
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610Note that leading zeros in a non-zero decimal number are not allowed. This is
611for disambiguation with C-style octal literals, which Python used before version
6123.0.
613
614Some examples of integer literals::
615
616 7 2147483647 0o177 0b100110111
617 3 79228162514264337593543950336 0o377 0x100000000
Georg Brandl06788c92009-01-03 21:31:47 +0000618 79228162514264337593543950336 0xdeadbeef
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620
621.. _floating:
622
623Floating point literals
624-----------------------
625
626Floating point literals are described by the following lexical definitions:
627
628.. productionlist::
629 floatnumber: `pointfloat` | `exponentfloat`
630 pointfloat: [`intpart`] `fraction` | `intpart` "."
631 exponentfloat: (`intpart` | `pointfloat`) `exponent`
632 intpart: `digit`+
633 fraction: "." `digit`+
634 exponent: ("e" | "E") ["+" | "-"] `digit`+
635
636Note that the integer and exponent parts are always interpreted using radix 10.
637For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The
638allowed range of floating point literals is implementation-dependent. Some
639examples of floating point literals::
640
641 3.14 10. .001 1e100 3.14e-10 0e0
642
643Note that numeric literals do not include a sign; a phrase like ``-1`` is
644actually an expression composed of the unary operator ``-`` and the literal
645``1``.
646
647
648.. _imaginary:
649
650Imaginary literals
651------------------
652
653Imaginary literals are described by the following lexical definitions:
654
655.. productionlist::
656 imagnumber: (`floatnumber` | `intpart`) ("j" | "J")
657
658An imaginary literal yields a complex number with a real part of 0.0. Complex
659numbers are represented as a pair of floating point numbers and have the same
660restrictions on their range. To create a complex number with a nonzero real
661part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
662imaginary literals::
663
Georg Brandl48310cd2009-01-03 21:18:54 +0000664 3.14j 10.j 10j .001j 1e100j 3.14e-10j
Georg Brandl116aa622007-08-15 14:28:22 +0000665
666
667.. _operators:
668
669Operators
670=========
671
672.. index:: single: operators
673
674The following tokens are operators::
675
676 + - * ** / // %
677 << >> & | ^ ~
678 < > <= >= == !=
679
680
681.. _delimiters:
682
683Delimiters
684==========
685
686.. index:: single: delimiters
687
688The following tokens serve as delimiters in the grammar::
689
Georg Brandl0df79792008-10-04 18:33:26 +0000690 ( ) [ ] { }
691 , : . ; @ =
Georg Brandl116aa622007-08-15 14:28:22 +0000692 += -= *= /= //= %=
693 &= |= ^= >>= <<= **=
694
695The period can also occur in floating-point and imaginary literals. A sequence
Georg Brandl57e3b682007-08-31 08:07:45 +0000696of three periods has a special meaning as an ellipsis literal. The second half
Georg Brandl116aa622007-08-15 14:28:22 +0000697of the list, the augmented assignment operators, serve lexically as delimiters,
698but also perform an operation.
699
700The following printing ASCII characters have special meaning as part of other
701tokens or are otherwise significant to the lexical analyzer::
702
703 ' " # \
704
Georg Brandl116aa622007-08-15 14:28:22 +0000705The following printing ASCII characters are not used in Python. Their
706occurrence outside string literals and comments is an unconditional error::
707
Georg Brandle43baab2010-05-10 21:17:00 +0000708 $ ? `