blob: b8ddacbbf1d75521509dce6e46278f7f042be71b [file] [log] [blame]
Fred Drakea1cce711998-07-24 22:12:32 +00001\chapter{Lexical analysis\label{lexical}}
Fred Drakef6669171998-05-06 19:52:49 +00002
Fred Drake5c07d9b1998-05-14 19:37:06 +00003A Python program is read by a \emph{parser}. Input to the parser is a
4stream of \emph{tokens}, generated by the \emph{lexical analyzer}. This
Fred Drakef6669171998-05-06 19:52:49 +00005chapter describes how the lexical analyzer breaks a file into tokens.
6\index{lexical analysis}
7\index{parser}
8\index{token}
9
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000010Python uses the 7-bit \ASCII{} character set for program text.
11\versionadded[An encoding declaration can be used to indicate that
12string literals and comments use an encoding different from ASCII.]{2.3}
13For compatibility with older versions, Python only warns if it finds
148-bit characters; those warnings should be corrected by either declaring
15an explicit encoding, or using escape sequences if those bytes are binary
16data, instead of characters.
17
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000018
19The run-time character set depends on the I/O devices connected to the
Fred Drakec37b65e2001-11-28 07:26:15 +000020program but is generally a superset of \ASCII.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000021
22\strong{Future compatibility note:} It may be tempting to assume that the
23character set for 8-bit characters is ISO Latin-1 (an \ASCII{}
24superset that covers most western languages that use the Latin
25alphabet), but it is possible that in the future Unicode text editors
26will become common. These generally use the UTF-8 encoding, which is
27also an \ASCII{} superset, but with very different use for the
28characters with ordinals 128-255. While there is no consensus on this
29subject yet, it is unwise to assume either Latin-1 or UTF-8, even
30though the current implementation appears to favor Latin-1. This
31applies both to the source character set and the run-time character
32set.
33
Fred Drakef5eae662001-06-23 05:26:52 +000034
Fred Drake61c77281998-07-28 19:34:22 +000035\section{Line structure\label{line-structure}}
Fred Drakef6669171998-05-06 19:52:49 +000036
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000037A Python program is divided into a number of \emph{logical lines}.
38\index{line structure}
39
Fred Drakef5eae662001-06-23 05:26:52 +000040
Fred Drake61c77281998-07-28 19:34:22 +000041\subsection{Logical lines\label{logical}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000042
43The end of
Fred Drakef6669171998-05-06 19:52:49 +000044a logical line is represented by the token NEWLINE. Statements cannot
45cross logical line boundaries except where NEWLINE is allowed by the
Guido van Rossum7c0240f1998-07-24 15:36:43 +000046syntax (e.g., between statements in compound statements).
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000047A logical line is constructed from one or more \emph{physical lines}
48by following the explicit or implicit \emph{line joining} rules.
Fred Drakef6669171998-05-06 19:52:49 +000049\index{logical line}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000050\index{physical line}
51\index{line joining}
Fred Drakef6669171998-05-06 19:52:49 +000052\index{NEWLINE token}
53
Fred Drakef5eae662001-06-23 05:26:52 +000054
Fred Drake61c77281998-07-28 19:34:22 +000055\subsection{Physical lines\label{physical}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000056
57A physical line ends in whatever the current platform's convention is
Fred Drakec37b65e2001-11-28 07:26:15 +000058for terminating lines. On \UNIX, this is the \ASCII{} LF (linefeed)
Martin v. Löwis36a4d8c2002-10-10 18:24:54 +000059character. On Windows, it is the \ASCII{} sequence CR LF (return
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000060followed by linefeed). On Macintosh, it is the \ASCII{} CR (return)
61character.
62
Fred Drakef5eae662001-06-23 05:26:52 +000063
Fred Drake61c77281998-07-28 19:34:22 +000064\subsection{Comments\label{comments}}
Fred Drakef6669171998-05-06 19:52:49 +000065
Fred Drake5c07d9b1998-05-14 19:37:06 +000066A comment starts with a hash character (\code{\#}) that is not part of
Fred Drakef6669171998-05-06 19:52:49 +000067a string literal, and ends at the end of the physical line. A comment
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000068signifies the end of the logical line unless the implicit line joining
69rules are invoked.
70Comments are ignored by the syntax; they are not tokens.
Fred Drakef6669171998-05-06 19:52:49 +000071\index{comment}
Fred Drakef6669171998-05-06 19:52:49 +000072\index{hash character}
73
Fred Drakef5eae662001-06-23 05:26:52 +000074
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000075\subsection{Encoding declarations\label{encodings}}
Martin v. Löwis266a4362004-09-14 07:52:22 +000076\index{source character set}
77\index{encodings}
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000078
79If a comment in the first or second line of the Python script matches
Martin v. Löwisae075b62004-08-18 13:25:05 +000080the regular expression \regexp{coding[=:]\e s*([-\e w.]+)}, this comment is
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000081processed as an encoding declaration; the first group of this
82expression names the encoding of the source code file. The recommended
83forms of this expression are
84
85\begin{verbatim}
86# -*- coding: <encoding-name> -*-
87\end{verbatim}
88
89which is recognized also by GNU Emacs, and
90
91\begin{verbatim}
92# vim:fileencoding=<encoding-name>
93\end{verbatim}
94
Raymond Hettinger3fd97792004-02-08 20:18:26 +000095which is recognized by Bram Moolenaar's VIM. In addition, if the first
Fred Drake31f3db32002-08-06 21:36:06 +000096bytes of the file are the UTF-8 byte-order mark
97(\code{'\e xef\e xbb\e xbf'}), the declared file encoding is UTF-8
98(this is supported, among others, by Microsoft's \program{notepad}).
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000099
100If an encoding is declared, the encoding name must be recognized by
101Python. % XXX there should be a list of supported encodings.
102The encoding is used for all lexical analysis, in particular to find
103the end of a string, and to interpret the contents of Unicode literals.
104String literals are converted to Unicode for syntactical analysis,
105then converted back to their original encoding before interpretation
Martin v. Löwisf62a89b2002-09-03 11:52:44 +0000106starts. The encoding declaration must appear on a line of its own.
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000107
Fred Drake61c77281998-07-28 19:34:22 +0000108\subsection{Explicit line joining\label{explicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000109
110Two or more physical lines may be joined into logical lines using
Fred Drake5c07d9b1998-05-14 19:37:06 +0000111backslash characters (\code{\e}), as follows: when a physical line ends
Fred Drakef6669171998-05-06 19:52:49 +0000112in a backslash that is not part of a string literal or comment, it is
113joined with the following forming a single logical line, deleting the
114backslash and the following end-of-line character. For example:
115\index{physical line}
116\index{line joining}
117\index{line continuation}
118\index{backslash character}
119%
120\begin{verbatim}
121if 1900 < year < 2100 and 1 <= month <= 12 \
122 and 1 <= day <= 31 and 0 <= hour < 24 \
123 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
124 return 1
125\end{verbatim}
126
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000127A line ending in a backslash cannot carry a comment. A backslash does
128not continue a comment. A backslash does not continue a token except
129for string literals (i.e., tokens other than string literals cannot be
130split across physical lines using a backslash). A backslash is
131illegal elsewhere on a line outside a string literal.
Fred Drakef6669171998-05-06 19:52:49 +0000132
Fred Drakec411fa61999-02-22 14:32:18 +0000133
Fred Drake61c77281998-07-28 19:34:22 +0000134\subsection{Implicit line joining\label{implicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000135
136Expressions in parentheses, square brackets or curly braces can be
137split over more than one physical line without using backslashes.
138For example:
139
140\begin{verbatim}
141month_names = ['Januari', 'Februari', 'Maart', # These are the
142 'April', 'Mei', 'Juni', # Dutch names
143 'Juli', 'Augustus', 'September', # for the months
144 'Oktober', 'November', 'December'] # of the year
145\end{verbatim}
146
147Implicitly continued lines can carry comments. The indentation of the
148continuation lines is not important. Blank continuation lines are
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000149allowed. There is no NEWLINE token between implicit continuation
150lines. Implicitly continued lines can also occur within triple-quoted
151strings (see below); in that case they cannot carry comments.
Fred Drakef6669171998-05-06 19:52:49 +0000152
Fred Drakef6669171998-05-06 19:52:49 +0000153
Fred Drake79713fd2002-10-24 19:57:37 +0000154\subsection{Blank lines \label{blank-lines}}
Fred Drakec411fa61999-02-22 14:32:18 +0000155
Fred Drake79713fd2002-10-24 19:57:37 +0000156\index{blank line}
Fred Drakec411fa61999-02-22 14:32:18 +0000157A logical line that contains only spaces, tabs, formfeeds and possibly
158a comment, is ignored (i.e., no NEWLINE token is generated). During
159interactive input of statements, handling of a blank line may differ
160depending on the implementation of the read-eval-print loop. In the
161standard implementation, an entirely blank logical line (i.e.\ one
162containing not even whitespace or a comment) terminates a multi-line
163statement.
164
Fred Drakef6669171998-05-06 19:52:49 +0000165
Fred Drake61c77281998-07-28 19:34:22 +0000166\subsection{Indentation\label{indentation}}
Fred Drakef6669171998-05-06 19:52:49 +0000167
168Leading whitespace (spaces and tabs) at the beginning of a logical
169line is used to compute the indentation level of the line, which in
170turn is used to determine the grouping of statements.
171\index{indentation}
172\index{whitespace}
173\index{leading whitespace}
174\index{space}
175\index{tab}
176\index{grouping}
177\index{statement grouping}
178
179First, tabs are replaced (from left to right) by one to eight spaces
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000180such that the total number of characters up to and including the
181replacement is a multiple of
Fred Drakec37b65e2001-11-28 07:26:15 +0000182eight (this is intended to be the same rule as used by \UNIX). The
Fred Drakef6669171998-05-06 19:52:49 +0000183total number of spaces preceding the first non-blank character then
184determines the line's indentation. Indentation cannot be split over
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000185multiple physical lines using backslashes; the whitespace up to the
186first backslash determines the indentation.
187
188\strong{Cross-platform compatibility note:} because of the nature of
189text editors on non-UNIX platforms, it is unwise to use a mixture of
Martin v. Löwis171be762003-06-21 13:40:02 +0000190spaces and tabs for the indentation in a single source file. It
191should also be noted that different platforms may explicitly limit the
192maximum indentation level.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000193
194A formfeed character may be present at the start of the line; it will
Fred Drakee15956b2000-04-03 04:51:13 +0000195be ignored for the indentation calculations above. Formfeed
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000196characters occurring elsewhere in the leading whitespace have an
197undefined effect (for instance, they may reset the space count to
198zero).
Fred Drakef6669171998-05-06 19:52:49 +0000199
200The indentation levels of consecutive lines are used to generate
201INDENT and DEDENT tokens, using a stack, as follows.
202\index{INDENT token}
203\index{DEDENT token}
204
205Before the first line of the file is read, a single zero is pushed on
206the stack; this will never be popped off again. The numbers pushed on
207the stack will always be strictly increasing from bottom to top. At
208the beginning of each logical line, the line's indentation level is
209compared to the top of the stack. If it is equal, nothing happens.
210If it is larger, it is pushed on the stack, and one INDENT token is
Fred Drake5c07d9b1998-05-14 19:37:06 +0000211generated. If it is smaller, it \emph{must} be one of the numbers
Fred Drakef6669171998-05-06 19:52:49 +0000212occurring on the stack; all numbers on the stack that are larger are
213popped off, and for each number popped off a DEDENT token is
214generated. At the end of the file, a DEDENT token is generated for
215each number remaining on the stack that is larger than zero.
216
217Here is an example of a correctly (though confusingly) indented piece
218of Python code:
219
220\begin{verbatim}
221def perm(l):
222 # Compute the list of all permutations of l
Fred Drakef6669171998-05-06 19:52:49 +0000223 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\end{verbatim}
233
234The following example shows various indentation errors:
235
236\begin{verbatim}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000237 def perm(l): # error: first line indented
238for i in range(len(l)): # error: not indented
239 s = l[:i] + l[i+1:]
240 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
241 for x in p:
242 r.append(l[i:i+1] + x)
243 return r # error: inconsistent dedent
Fred Drakef6669171998-05-06 19:52:49 +0000244\end{verbatim}
245
246(Actually, the first three errors are detected by the parser; only the
247last error is found by the lexical analyzer --- the indentation of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000248\code{return r} does not match a level popped off the stack.)
Fred Drakef6669171998-05-06 19:52:49 +0000249
Fred Drakef5eae662001-06-23 05:26:52 +0000250
Fred Drake61c77281998-07-28 19:34:22 +0000251\subsection{Whitespace between tokens\label{whitespace}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000252
253Except at the beginning of a logical line or in string literals, the
254whitespace characters space, tab and formfeed can be used
255interchangeably to separate tokens. Whitespace is needed between two
256tokens only if their concatenation could otherwise be interpreted as a
257different token (e.g., ab is one token, but a b is two tokens).
258
Fred Drakef5eae662001-06-23 05:26:52 +0000259
Fred Drake61c77281998-07-28 19:34:22 +0000260\section{Other tokens\label{other-tokens}}
Fred Drakef6669171998-05-06 19:52:49 +0000261
262Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000263exist: \emph{identifiers}, \emph{keywords}, \emph{literals},
264\emph{operators}, and \emph{delimiters}.
265Whitespace characters (other than line terminators, discussed earlier)
266are not tokens, but serve to delimit tokens.
267Where
Fred Drakef6669171998-05-06 19:52:49 +0000268ambiguity exists, a token comprises the longest possible string that
269forms a legal token, when read from left to right.
270
Fred Drakef5eae662001-06-23 05:26:52 +0000271
Fred Drake61c77281998-07-28 19:34:22 +0000272\section{Identifiers and keywords\label{identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +0000273
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000274Identifiers (also referred to as \emph{names}) are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000275lexical definitions:
276\index{identifier}
277\index{name}
278
Fred Drakecb4638a2001-07-06 22:49:53 +0000279\begin{productionlist}
280 \production{identifier}
281 {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
282 \production{letter}
283 {\token{lowercase} | \token{uppercase}}
284 \production{lowercase}
285 {"a"..."z"}
286 \production{uppercase}
287 {"A"..."Z"}
288 \production{digit}
289 {"0"..."9"}
290\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000291
292Identifiers are unlimited in length. Case is significant.
293
Fred Drakef5eae662001-06-23 05:26:52 +0000294
Fred Drake61c77281998-07-28 19:34:22 +0000295\subsection{Keywords\label{keywords}}
Fred Drakef6669171998-05-06 19:52:49 +0000296
Fred Drake5c07d9b1998-05-14 19:37:06 +0000297The following identifiers are used as reserved words, or
298\emph{keywords} of the language, and cannot be used as ordinary
299identifiers. They must be spelled exactly as written here:%
300\index{keyword}%
Fred Drakef6669171998-05-06 19:52:49 +0000301\index{reserved word}
302
303\begin{verbatim}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000304and del for is raise
305assert elif from lambda return
306break else global not try
Guido van Rossum41c67192001-12-04 20:38:44 +0000307class except if or while
308continue exec import pass yield
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000309def finally in print
Fred Drakef6669171998-05-06 19:52:49 +0000310\end{verbatim}
311
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000312% When adding keywords, use reswords.py for reformatting
313
Fred Drakea23b5732002-06-18 19:17:14 +0000314Note that although the identifier \code{as} can be used as part of the
315syntax of \keyword{import} statements, it is not currently a reserved
316word.
317
318In some future version of Python, the identifiers \code{as} and
319\code{None} will both become keywords.
320
Fred Drakef5eae662001-06-23 05:26:52 +0000321
Fred Drake61c77281998-07-28 19:34:22 +0000322\subsection{Reserved classes of identifiers\label{id-classes}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000323
324Certain classes of identifiers (besides keywords) have special
Fred Drake38f6b882003-09-06 03:50:07 +0000325meanings. These classes are identified by the patterns of leading and
326trailing underscore characters:
Fred Drake39fc1bc1999-03-05 18:30:21 +0000327
328\begin{description}
Fred Drake38f6b882003-09-06 03:50:07 +0000329
330\item[\code{_*}]
331 Not imported by \samp{from \var{module} import *}. The special
332 identifier \samp{_} is used in the interactive interpreter to store
333 the result of the last evaluation; it is stored in the
334 \module{__builtin__} module. When not in interactive mode, \samp{_}
335 has no special meaning and is not defined.
336 See section~\ref{import}, ``The \keyword{import} statement.''
337
338 \note{The name \samp{_} is often used in conjunction with
339 internationalization; refer to the documentation for the
340 \ulink{\module{gettext} module}{../lib/module-gettext.html} for more
341 information on this convention.}
342
343\item[\code{__*__}]
344 System-defined names. These names are defined by the interpreter
345 and it's implementation (including the standard library);
346 applications should not expect to define additional names using this
347 convention. The set of names of this class defined by Python may be
348 extended in future versions.
349 See section~\ref{specialnames}, ``Special method names.''
350
351\item[\code{__*}]
352 Class-private names. Names in this category, when used within the
Martin v. Löwis13ff1162004-06-02 12:48:20 +0000353 context of a class definition, are re-written to use a mangled form
Fred Drake38f6b882003-09-06 03:50:07 +0000354 to help avoid name clashes between ``private'' attributes of base
355 and derived classes.
356 See section~\ref{atom-identifiers}, ``Identifiers (Names).''
357
Fred Drake39fc1bc1999-03-05 18:30:21 +0000358\end{description}
359
360
Fred Drake61c77281998-07-28 19:34:22 +0000361\section{Literals\label{literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000362
363Literals are notations for constant values of some built-in types.
364\index{literal}
365\index{constant}
366
Fred Drakef5eae662001-06-23 05:26:52 +0000367
Fred Drake61c77281998-07-28 19:34:22 +0000368\subsection{String literals\label{strings}}
Fred Drakef6669171998-05-06 19:52:49 +0000369
370String literals are described by the following lexical definitions:
371\index{string literal}
372
Fred Drakec37b65e2001-11-28 07:26:15 +0000373\index{ASCII@\ASCII}
Fred Drakecb4638a2001-07-06 22:49:53 +0000374\begin{productionlist}
375 \production{stringliteral}
Fred Drakec0cf7262001-08-14 21:43:31 +0000376 {[\token{stringprefix}](\token{shortstring} | \token{longstring})}
377 \production{stringprefix}
378 {"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000379 \production{shortstring}
380 {"'" \token{shortstringitem}* "'"
381 | '"' \token{shortstringitem}* '"'}
382 \production{longstring}
Fred Drake53815882002-03-15 23:21:37 +0000383 {"'''" \token{longstringitem}* "'''"}
384 \productioncont{| '"""' \token{longstringitem}* '"""'}
Fred Drakecb4638a2001-07-06 22:49:53 +0000385 \production{shortstringitem}
386 {\token{shortstringchar} | \token{escapeseq}}
387 \production{longstringitem}
388 {\token{longstringchar} | \token{escapeseq}}
389 \production{shortstringchar}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000390 {<any source character except "\e" or newline or the quote>}
Fred Drakecb4638a2001-07-06 22:49:53 +0000391 \production{longstringchar}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000392 {<any source character except "\e">}
Fred Drakecb4638a2001-07-06 22:49:53 +0000393 \production{escapeseq}
394 {"\e" <any ASCII character>}
395\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000396
Fred Drakec0cf7262001-08-14 21:43:31 +0000397One syntactic restriction not indicated by these productions is that
398whitespace is not allowed between the \grammartoken{stringprefix} and
Martin v. Löwis266a4362004-09-14 07:52:22 +0000399the rest of the string literal. The source character set is defined
Fred Drake5b000592004-11-10 16:51:17 +0000400by the encoding declaration; it is \ASCII{} if no encoding declaration
401is given in the source file; see section~\ref{encodings}.
Fred Drakec0cf7262001-08-14 21:43:31 +0000402
Fred Drakedea764d2000-12-19 04:52:03 +0000403\index{triple-quoted string}
404\index{Unicode Consortium}
405\index{string!Unicode}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000406In plain English: String literals can be enclosed in matching single
407quotes (\code{'}) or double quotes (\code{"}). They can also be
408enclosed in matching groups of three single or double quotes (these
409are generally referred to as \emph{triple-quoted strings}). The
410backslash (\code{\e}) character is used to escape characters that
411otherwise have a special meaning, such as newline, backslash itself,
412or the quote character. String literals may optionally be prefixed
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000413with a letter \character{r} or \character{R}; such strings are called
414\dfn{raw strings}\index{raw string} and use different rules for interpreting
415backslash escape sequences. A prefix of \character{u} or \character{U}
416makes the string a Unicode string. Unicode strings use the Unicode character
417set as defined by the Unicode Consortium and ISO~10646. Some additional
Fred Drakedea764d2000-12-19 04:52:03 +0000418escape sequences, described below, are available in Unicode strings.
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000419The two prefix characters may be combined; in this case, \character{u} must
420appear before \character{r}.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000421
422In triple-quoted strings,
Fred Drakef6669171998-05-06 19:52:49 +0000423unescaped newlines and quotes are allowed (and are retained), except
424that three unescaped quotes in a row terminate the string. (A
425``quote'' is the character used to open the string, i.e. either
Fred Drake5c07d9b1998-05-14 19:37:06 +0000426\code{'} or \code{"}.)
Fred Drakef6669171998-05-06 19:52:49 +0000427
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000428Unless an \character{r} or \character{R} prefix is present, escape
429sequences in strings are interpreted according to rules similar
Fred Drake90791642001-07-20 15:33:23 +0000430to those used by Standard C. The recognized escape sequences are:
Fred Drakef6669171998-05-06 19:52:49 +0000431\index{physical line}
432\index{escape sequence}
433\index{Standard C}
434\index{C}
435
Fred Drake3e930ba2002-09-24 21:08:37 +0000436\begin{tableiii}{l|l|c}{code}{Escape Sequence}{Meaning}{Notes}
437\lineiii{\e\var{newline}} {Ignored}{}
438\lineiii{\e\e} {Backslash (\code{\e})}{}
439\lineiii{\e'} {Single quote (\code{'})}{}
440\lineiii{\e"} {Double quote (\code{"})}{}
441\lineiii{\e a} {\ASCII{} Bell (BEL)}{}
442\lineiii{\e b} {\ASCII{} Backspace (BS)}{}
443\lineiii{\e f} {\ASCII{} Formfeed (FF)}{}
444\lineiii{\e n} {\ASCII{} Linefeed (LF)}{}
445\lineiii{\e N\{\var{name}\}}
446 {Character named \var{name} in the Unicode database (Unicode only)}{}
447\lineiii{\e r} {\ASCII{} Carriage Return (CR)}{}
448\lineiii{\e t} {\ASCII{} Horizontal Tab (TAB)}{}
449\lineiii{\e u\var{xxxx}}
450 {Character with 16-bit hex value \var{xxxx} (Unicode only)}{(1)}
451\lineiii{\e U\var{xxxxxxxx}}
452 {Character with 32-bit hex value \var{xxxxxxxx} (Unicode only)}{(2)}
453\lineiii{\e v} {\ASCII{} Vertical Tab (VT)}{}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000454\lineiii{\e\var{ooo}} {Character with octal value \var{ooo}}{(3,5)}
455\lineiii{\e x\var{hh}} {Character with hex value \var{hh}}{(4,5)}
Fred Drake3e930ba2002-09-24 21:08:37 +0000456\end{tableiii}
Fred Drakec37b65e2001-11-28 07:26:15 +0000457\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000458
Fred Drake3e930ba2002-09-24 21:08:37 +0000459\noindent
460Notes:
461
462\begin{itemize}
463\item[(1)]
464 Individual code units which form parts of a surrogate pair can be
465 encoded using this escape sequence.
466\item[(2)]
467 Any Unicode character can be encoded this way, but characters
468 outside the Basic Multilingual Plane (BMP) will be encoded using a
469 surrogate pair if Python is compiled to use 16-bit code units (the
470 default). Individual code units which form parts of a surrogate
471 pair can be encoded using this escape sequence.
472\item[(3)]
473 As in Standard C, up to three octal digits are accepted.
474\item[(4)]
475 Unlike in Standard C, at most two hex digits are accepted.
Martin v. Löwis266a4362004-09-14 07:52:22 +0000476\item[(5)]
477 In a string literal, hexadecimal and octal escapes denote the
478 byte with the given value; it is not necessary that the byte
479 encodes a character in the source character set. In a Unicode
480 literal, these escapes denote a Unicode character with the given
481 value.
Fred Drake3e930ba2002-09-24 21:08:37 +0000482\end{itemize}
483
Fred Drakef6669171998-05-06 19:52:49 +0000484
Fred Drakedea764d2000-12-19 04:52:03 +0000485Unlike Standard \index{unrecognized escape sequence}C,
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000486all unrecognized escape sequences are left in the string unchanged,
Fred Drakedea764d2000-12-19 04:52:03 +0000487i.e., \emph{the backslash is left in the string}. (This behavior is
Fred Drakef6669171998-05-06 19:52:49 +0000488useful when debugging: if an escape sequence is mistyped, the
Fred Drakedea764d2000-12-19 04:52:03 +0000489resulting output is more easily recognized as broken.) It is also
490important to note that the escape sequences marked as ``(Unicode
491only)'' in the table above fall into the category of unrecognized
492escapes for non-Unicode string literals.
Fred Drakef6669171998-05-06 19:52:49 +0000493
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000494When an \character{r} or \character{R} prefix is present, a character
495following a backslash is included in the string without change, and \emph{all
Fred Drake347a6252001-01-09 21:38:16 +0000496backslashes are left in the string}. For example, the string literal
497\code{r"\e n"} consists of two characters: a backslash and a lowercase
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000498\character{n}. String quotes can be escaped with a backslash, but the
499backslash remains in the string; for example, \code{r"\e""} is a valid string
Fred Drake347a6252001-01-09 21:38:16 +0000500literal consisting of two characters: a backslash and a double quote;
Fred Drake0825dc22001-07-20 14:32:28 +0000501\code{r"\e"} is not a valid string literal (even a raw string cannot
Fred Drake347a6252001-01-09 21:38:16 +0000502end in an odd number of backslashes). Specifically, \emph{a raw
503string cannot end in a single backslash} (since the backslash would
504escape the following quote character). Note also that a single
505backslash followed by a newline is interpreted as those two characters
506as part of the string, \emph{not} as a line continuation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000507
Fred Drakef7aa1642002-08-07 13:24:09 +0000508When an \character{r} or \character{R} prefix is used in conjunction
509with a \character{u} or \character{U} prefix, then the \code{\e uXXXX}
510escape sequence is processed while \emph{all other backslashes are
Fred Drake3e930ba2002-09-24 21:08:37 +0000511left in the string}. For example, the string literal
512\code{ur"\e{}u0062\e n"} consists of three Unicode characters: `LATIN
513SMALL LETTER B', `REVERSE SOLIDUS', and `LATIN SMALL LETTER N'.
514Backslashes can be escaped with a preceding backslash; however, both
515remain in the string. As a result, \code{\e uXXXX} escape sequences
516are only recognized when there are an odd number of backslashes.
Fred Drakef5eae662001-06-23 05:26:52 +0000517
Fred Drake61c77281998-07-28 19:34:22 +0000518\subsection{String literal concatenation\label{string-catenation}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000519
520Multiple adjacent string literals (delimited by whitespace), possibly
521using different quoting conventions, are allowed, and their meaning is
522the same as their concatenation. Thus, \code{"hello" 'world'} is
523equivalent to \code{"helloworld"}. This feature can be used to reduce
524the number of backslashes needed, to split long strings conveniently
525across long lines, or even to add comments to parts of strings, for
526example:
527
528\begin{verbatim}
529re.compile("[A-Za-z_]" # letter or underscore
530 "[A-Za-z0-9_]*" # letter, digit or underscore
531 )
532\end{verbatim}
533
534Note that this feature is defined at the syntactical level, but
535implemented at compile time. The `+' operator must be used to
536concatenate string expressions at run time. Also note that literal
537concatenation can use different quoting styles for each component
538(even mixing raw strings and triple quoted strings).
539
Fred Drake2ed27d32000-11-17 19:05:12 +0000540
Fred Drake61c77281998-07-28 19:34:22 +0000541\subsection{Numeric literals\label{numbers}}
Fred Drakef6669171998-05-06 19:52:49 +0000542
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000543There are four types of numeric literals: plain integers, long
544integers, floating point numbers, and imaginary numbers. There are no
545complex literals (complex numbers can be formed by adding a real
546number and an imaginary number).
Fred Drakef6669171998-05-06 19:52:49 +0000547\index{number}
548\index{numeric literal}
549\index{integer literal}
550\index{plain integer literal}
551\index{long integer literal}
552\index{floating point literal}
553\index{hexadecimal literal}
554\index{octal literal}
555\index{decimal literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000556\index{imaginary literal}
Fred Drakeed9e4532002-04-23 20:04:46 +0000557\index{complex!literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000558
559Note that numeric literals do not include a sign; a phrase like
560\code{-1} is actually an expression composed of the unary operator
561`\code{-}' and the literal \code{1}.
562
Fred Drakef5eae662001-06-23 05:26:52 +0000563
Fred Drake61c77281998-07-28 19:34:22 +0000564\subsection{Integer and long integer literals\label{integers}}
Fred Drakef6669171998-05-06 19:52:49 +0000565
566Integer and long integer literals are described by the following
567lexical definitions:
568
Fred Drakecb4638a2001-07-06 22:49:53 +0000569\begin{productionlist}
570 \production{longinteger}
571 {\token{integer} ("l" | "L")}
572 \production{integer}
573 {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
574 \production{decimalinteger}
575 {\token{nonzerodigit} \token{digit}* | "0"}
576 \production{octinteger}
577 {"0" \token{octdigit}+}
578 \production{hexinteger}
579 {"0" ("x" | "X") \token{hexdigit}+}
580 \production{nonzerodigit}
581 {"1"..."9"}
582 \production{octdigit}
583 {"0"..."7"}
584 \production{hexdigit}
585 {\token{digit} | "a"..."f" | "A"..."F"}
586\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000587
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000588Although both lower case \character{l} and upper case \character{L} are
589allowed as suffix for long integers, it is strongly recommended to always
590use \character{L}, since the letter \character{l} looks too much like the
591digit \character{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000592
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000593Plain integer literals that are above the largest representable plain
594integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
595as if they were long integers instead.\footnote{In versions of Python
596prior to 2.4, octal and hexadecimal literals in the range just above
597the largest representable plain integer but below the largest unsigned
59832-bit number (on a machine using 32-bit arithmetic), 4294967296, were
599taken as the negative plain integer obtained by subtracting 4294967296
600from their unsigned value.} There is no limit for long integer
601literals apart from what can be stored in available memory.
Fred Drakef6669171998-05-06 19:52:49 +0000602
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000603Some examples of plain integer literals (first row) and long integer
604literals (second and third rows):
Fred Drakef6669171998-05-06 19:52:49 +0000605
606\begin{verbatim}
Guido van Rossum6c9e1302003-11-29 23:52:13 +00006077 2147483647 0177
Fred Drakef6669171998-05-06 19:52:49 +00006083L 79228162514264337593543950336L 0377L 0x100000000L
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000609 79228162514264337593543950336 0xdeadbeef
Fred Drakef6669171998-05-06 19:52:49 +0000610\end{verbatim}
611
Fred Drakef5eae662001-06-23 05:26:52 +0000612
Fred Drake61c77281998-07-28 19:34:22 +0000613\subsection{Floating point literals\label{floating}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000614
Fred Drakef6669171998-05-06 19:52:49 +0000615Floating point literals are described by the following lexical
616definitions:
617
Fred Drakecb4638a2001-07-06 22:49:53 +0000618\begin{productionlist}
619 \production{floatnumber}
620 {\token{pointfloat} | \token{exponentfloat}}
621 \production{pointfloat}
622 {[\token{intpart}] \token{fraction} | \token{intpart} "."}
623 \production{exponentfloat}
Tim Petersd507dab2001-08-30 20:51:59 +0000624 {(\token{intpart} | \token{pointfloat})
Fred Drakecb4638a2001-07-06 22:49:53 +0000625 \token{exponent}}
626 \production{intpart}
Tim Petersd507dab2001-08-30 20:51:59 +0000627 {\token{digit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000628 \production{fraction}
629 {"." \token{digit}+}
630 \production{exponent}
631 {("e" | "E") ["+" | "-"] \token{digit}+}
632\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000633
Tim Petersd507dab2001-08-30 20:51:59 +0000634Note that the integer and exponent parts of floating point numbers
635can look like octal integers, but are interpreted using radix 10. For
636example, \samp{077e010} is legal, and denotes the same number
637as \samp{77e10}.
Fred Drakef6669171998-05-06 19:52:49 +0000638The allowed range of floating point literals is
639implementation-dependent.
Fred Drakef6669171998-05-06 19:52:49 +0000640Some examples of floating point literals:
641
642\begin{verbatim}
Tim Petersd507dab2001-08-30 20:51:59 +00006433.14 10. .001 1e100 3.14e-10 0e0
Fred Drakef6669171998-05-06 19:52:49 +0000644\end{verbatim}
645
646Note that numeric literals do not include a sign; a phrase like
Fred Drake5c07d9b1998-05-14 19:37:06 +0000647\code{-1} is actually an expression composed of the operator
648\code{-} and the literal \code{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000649
Fred Drakef5eae662001-06-23 05:26:52 +0000650
Fred Drake61c77281998-07-28 19:34:22 +0000651\subsection{Imaginary literals\label{imaginary}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000652
653Imaginary literals are described by the following lexical definitions:
654
Fred Drakecb4638a2001-07-06 22:49:53 +0000655\begin{productionlist}
656 \production{imagnumber}{(\token{floatnumber} | \token{intpart}) ("j" | "J")}
657\end{productionlist}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000658
Fred Drakee15956b2000-04-03 04:51:13 +0000659An imaginary literal yields a complex number with a real part of
Guido van Rossum60f2f0c1998-06-15 18:00:50 +00006600.0. Complex numbers are represented as a pair of floating point
661numbers and have the same restrictions on their range. To create a
662complex number with a nonzero real part, add a floating point number
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000663to it, e.g., \code{(3+4j)}. Some examples of imaginary literals:
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000664
665\begin{verbatim}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00006663.14j 10.j 10j .001j 1e100j 3.14e-10j
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000667\end{verbatim}
668
669
Fred Drake61c77281998-07-28 19:34:22 +0000670\section{Operators\label{operators}}
Fred Drakef6669171998-05-06 19:52:49 +0000671
672The following tokens are operators:
673\index{operators}
674
675\begin{verbatim}
Fred Drakea7d608d2001-08-08 05:37:21 +0000676+ - * ** / // %
Fred Drakef6669171998-05-06 19:52:49 +0000677<< >> & | ^ ~
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000678< > <= >= == != <>
Fred Drakef6669171998-05-06 19:52:49 +0000679\end{verbatim}
680
Fred Drake5c07d9b1998-05-14 19:37:06 +0000681The comparison operators \code{<>} and \code{!=} are alternate
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000682spellings of the same operator. \code{!=} is the preferred spelling;
683\code{<>} is obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000684
Fred Drakef5eae662001-06-23 05:26:52 +0000685
Fred Drake61c77281998-07-28 19:34:22 +0000686\section{Delimiters\label{delimiters}}
Fred Drakef6669171998-05-06 19:52:49 +0000687
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000688The following tokens serve as delimiters in the grammar:
Fred Drakef6669171998-05-06 19:52:49 +0000689\index{delimiters}
690
691\begin{verbatim}
Fred Drake6bd8e842004-08-05 21:11:27 +0000692( ) [ ] { } @
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000693, : . ` = ;
Fred Drakea7d608d2001-08-08 05:37:21 +0000694+= -= *= /= //= %=
695&= |= ^= >>= <<= **=
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000696\end{verbatim}
697
698The period can also occur in floating-point and imaginary literals. A
Fred Drakee15956b2000-04-03 04:51:13 +0000699sequence of three periods has a special meaning as an ellipsis in slices.
Thomas Wouters12bba852000-08-24 20:06:04 +0000700The second half of the list, the augmented assignment operators, serve
701lexically as delimiters, but also perform an operation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000702
Fred Drakec37b65e2001-11-28 07:26:15 +0000703The following printing \ASCII{} characters have special meaning as part
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000704of other tokens or are otherwise significant to the lexical analyzer:
705
706\begin{verbatim}
707' " # \
Fred Drakef6669171998-05-06 19:52:49 +0000708\end{verbatim}
709
710The following printing \ASCII{} characters are not used in Python. Their
711occurrence outside string literals and comments is an unconditional
712error:
Fred Drakec37b65e2001-11-28 07:26:15 +0000713\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000714
715\begin{verbatim}
Fred Drake6bd8e842004-08-05 21:11:27 +0000716$ ?
Fred Drakef6669171998-05-06 19:52:49 +0000717\end{verbatim}