blob: e0f1e49dfe8bd997132e6f91923b7115e85acf7b [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}}
76
77If a comment in the first or second line of the Python script matches
Fred Drake31f3db32002-08-06 21:36:06 +000078the regular expression \regexp{coding[=:]\e s*([\e w-_.]+)}, this comment is
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000079processed as an encoding declaration; the first group of this
80expression names the encoding of the source code file. The recommended
81forms of this expression are
82
83\begin{verbatim}
84# -*- coding: <encoding-name> -*-
85\end{verbatim}
86
87which is recognized also by GNU Emacs, and
88
89\begin{verbatim}
90# vim:fileencoding=<encoding-name>
91\end{verbatim}
92
93which is recognized by Bram Moolenar's VIM. In addition, if the first
Fred Drake31f3db32002-08-06 21:36:06 +000094bytes of the file are the UTF-8 byte-order mark
95(\code{'\e xef\e xbb\e xbf'}), the declared file encoding is UTF-8
96(this is supported, among others, by Microsoft's \program{notepad}).
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000097
98If an encoding is declared, the encoding name must be recognized by
99Python. % XXX there should be a list of supported encodings.
100The encoding is used for all lexical analysis, in particular to find
101the end of a string, and to interpret the contents of Unicode literals.
102String literals are converted to Unicode for syntactical analysis,
103then converted back to their original encoding before interpretation
Martin v. Löwisf62a89b2002-09-03 11:52:44 +0000104starts. The encoding declaration must appear on a line of its own.
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000105
Fred Drake61c77281998-07-28 19:34:22 +0000106\subsection{Explicit line joining\label{explicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000107
108Two or more physical lines may be joined into logical lines using
Fred Drake5c07d9b1998-05-14 19:37:06 +0000109backslash characters (\code{\e}), as follows: when a physical line ends
Fred Drakef6669171998-05-06 19:52:49 +0000110in a backslash that is not part of a string literal or comment, it is
111joined with the following forming a single logical line, deleting the
112backslash and the following end-of-line character. For example:
113\index{physical line}
114\index{line joining}
115\index{line continuation}
116\index{backslash character}
117%
118\begin{verbatim}
119if 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\end{verbatim}
124
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000125A line ending in a backslash cannot carry a comment. A backslash does
126not continue a comment. A backslash does not continue a token except
127for string literals (i.e., tokens other than string literals cannot be
128split across physical lines using a backslash). A backslash is
129illegal elsewhere on a line outside a string literal.
Fred Drakef6669171998-05-06 19:52:49 +0000130
Fred Drakec411fa61999-02-22 14:32:18 +0000131
Fred Drake61c77281998-07-28 19:34:22 +0000132\subsection{Implicit line joining\label{implicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000133
134Expressions in parentheses, square brackets or curly braces can be
135split over more than one physical line without using backslashes.
136For example:
137
138\begin{verbatim}
139month_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\end{verbatim}
144
145Implicitly continued lines can carry comments. The indentation of the
146continuation lines is not important. Blank continuation lines are
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000147allowed. There is no NEWLINE token between implicit continuation
148lines. Implicitly continued lines can also occur within triple-quoted
149strings (see below); in that case they cannot carry comments.
Fred Drakef6669171998-05-06 19:52:49 +0000150
Fred Drakef6669171998-05-06 19:52:49 +0000151
Fred Drake79713fd2002-10-24 19:57:37 +0000152\subsection{Blank lines \label{blank-lines}}
Fred Drakec411fa61999-02-22 14:32:18 +0000153
Fred Drake79713fd2002-10-24 19:57:37 +0000154\index{blank line}
Fred Drakec411fa61999-02-22 14:32:18 +0000155A logical line that contains only spaces, tabs, formfeeds and possibly
156a comment, is ignored (i.e., no NEWLINE token is generated). During
157interactive input of statements, handling of a blank line may differ
158depending on the implementation of the read-eval-print loop. In the
159standard implementation, an entirely blank logical line (i.e.\ one
160containing not even whitespace or a comment) terminates a multi-line
161statement.
162
Fred Drakef6669171998-05-06 19:52:49 +0000163
Fred Drake61c77281998-07-28 19:34:22 +0000164\subsection{Indentation\label{indentation}}
Fred Drakef6669171998-05-06 19:52:49 +0000165
166Leading whitespace (spaces and tabs) at the beginning of a logical
167line is used to compute the indentation level of the line, which in
168turn is used to determine the grouping of statements.
169\index{indentation}
170\index{whitespace}
171\index{leading whitespace}
172\index{space}
173\index{tab}
174\index{grouping}
175\index{statement grouping}
176
177First, tabs are replaced (from left to right) by one to eight spaces
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000178such that the total number of characters up to and including the
179replacement is a multiple of
Fred Drakec37b65e2001-11-28 07:26:15 +0000180eight (this is intended to be the same rule as used by \UNIX). The
Fred Drakef6669171998-05-06 19:52:49 +0000181total number of spaces preceding the first non-blank character then
182determines the line's indentation. Indentation cannot be split over
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000183multiple physical lines using backslashes; the whitespace up to the
184first backslash determines the indentation.
185
186\strong{Cross-platform compatibility note:} because of the nature of
187text editors on non-UNIX platforms, it is unwise to use a mixture of
Martin v. Löwis171be762003-06-21 13:40:02 +0000188spaces and tabs for the indentation in a single source file. It
189should also be noted that different platforms may explicitly limit the
190maximum indentation level.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000191
192A formfeed character may be present at the start of the line; it will
Fred Drakee15956b2000-04-03 04:51:13 +0000193be ignored for the indentation calculations above. Formfeed
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000194characters occurring elsewhere in the leading whitespace have an
195undefined effect (for instance, they may reset the space count to
196zero).
Fred Drakef6669171998-05-06 19:52:49 +0000197
198The indentation levels of consecutive lines are used to generate
199INDENT and DEDENT tokens, using a stack, as follows.
200\index{INDENT token}
201\index{DEDENT token}
202
203Before the first line of the file is read, a single zero is pushed on
204the stack; this will never be popped off again. The numbers pushed on
205the stack will always be strictly increasing from bottom to top. At
206the beginning of each logical line, the line's indentation level is
207compared to the top of the stack. If it is equal, nothing happens.
208If it is larger, it is pushed on the stack, and one INDENT token is
Fred Drake5c07d9b1998-05-14 19:37:06 +0000209generated. If it is smaller, it \emph{must} be one of the numbers
Fred Drakef6669171998-05-06 19:52:49 +0000210occurring on the stack; all numbers on the stack that are larger are
211popped off, and for each number popped off a DEDENT token is
212generated. At the end of the file, a DEDENT token is generated for
213each number remaining on the stack that is larger than zero.
214
215Here is an example of a correctly (though confusingly) indented piece
216of Python code:
217
218\begin{verbatim}
219def perm(l):
220 # Compute the list of all permutations of l
Fred Drakef6669171998-05-06 19:52:49 +0000221 if len(l) <= 1:
222 return [l]
223 r = []
224 for i in range(len(l)):
225 s = l[:i] + l[i+1:]
226 p = perm(s)
227 for x in p:
228 r.append(l[i:i+1] + x)
229 return r
230\end{verbatim}
231
232The following example shows various indentation errors:
233
234\begin{verbatim}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000235 def perm(l): # error: first line indented
236for 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
Fred Drakef6669171998-05-06 19:52:49 +0000242\end{verbatim}
243
244(Actually, the first three errors are detected by the parser; only the
245last error is found by the lexical analyzer --- the indentation of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000246\code{return r} does not match a level popped off the stack.)
Fred Drakef6669171998-05-06 19:52:49 +0000247
Fred Drakef5eae662001-06-23 05:26:52 +0000248
Fred Drake61c77281998-07-28 19:34:22 +0000249\subsection{Whitespace between tokens\label{whitespace}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000250
251Except at the beginning of a logical line or in string literals, the
252whitespace characters space, tab and formfeed can be used
253interchangeably to separate tokens. Whitespace is needed between two
254tokens only if their concatenation could otherwise be interpreted as a
255different token (e.g., ab is one token, but a b is two tokens).
256
Fred Drakef5eae662001-06-23 05:26:52 +0000257
Fred Drake61c77281998-07-28 19:34:22 +0000258\section{Other tokens\label{other-tokens}}
Fred Drakef6669171998-05-06 19:52:49 +0000259
260Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000261exist: \emph{identifiers}, \emph{keywords}, \emph{literals},
262\emph{operators}, and \emph{delimiters}.
263Whitespace characters (other than line terminators, discussed earlier)
264are not tokens, but serve to delimit tokens.
265Where
Fred Drakef6669171998-05-06 19:52:49 +0000266ambiguity exists, a token comprises the longest possible string that
267forms a legal token, when read from left to right.
268
Fred Drakef5eae662001-06-23 05:26:52 +0000269
Fred Drake61c77281998-07-28 19:34:22 +0000270\section{Identifiers and keywords\label{identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +0000271
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000272Identifiers (also referred to as \emph{names}) are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000273lexical definitions:
274\index{identifier}
275\index{name}
276
Fred Drakecb4638a2001-07-06 22:49:53 +0000277\begin{productionlist}
278 \production{identifier}
279 {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
280 \production{letter}
281 {\token{lowercase} | \token{uppercase}}
282 \production{lowercase}
283 {"a"..."z"}
284 \production{uppercase}
285 {"A"..."Z"}
286 \production{digit}
287 {"0"..."9"}
288\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000289
290Identifiers are unlimited in length. Case is significant.
291
Fred Drakef5eae662001-06-23 05:26:52 +0000292
Fred Drake61c77281998-07-28 19:34:22 +0000293\subsection{Keywords\label{keywords}}
Fred Drakef6669171998-05-06 19:52:49 +0000294
Fred Drake5c07d9b1998-05-14 19:37:06 +0000295The following identifiers are used as reserved words, or
296\emph{keywords} of the language, and cannot be used as ordinary
297identifiers. They must be spelled exactly as written here:%
298\index{keyword}%
Fred Drakef6669171998-05-06 19:52:49 +0000299\index{reserved word}
300
301\begin{verbatim}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000302and del for is raise
303assert elif from lambda return
304break else global not try
Guido van Rossum41c67192001-12-04 20:38:44 +0000305class except if or while
306continue exec import pass yield
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000307def finally in print
Fred Drakef6669171998-05-06 19:52:49 +0000308\end{verbatim}
309
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000310% When adding keywords, use reswords.py for reformatting
311
Fred Drakea23b5732002-06-18 19:17:14 +0000312Note that although the identifier \code{as} can be used as part of the
313syntax of \keyword{import} statements, it is not currently a reserved
314word.
315
316In some future version of Python, the identifiers \code{as} and
317\code{None} will both become keywords.
318
Fred Drakef5eae662001-06-23 05:26:52 +0000319
Fred Drake61c77281998-07-28 19:34:22 +0000320\subsection{Reserved classes of identifiers\label{id-classes}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000321
322Certain classes of identifiers (besides keywords) have special
323meanings. These are:
324
Fred Drake39fc1bc1999-03-05 18:30:21 +0000325\begin{tableiii}{l|l|l}{code}{Form}{Meaning}{Notes}
326\lineiii{_*}{Not imported by \samp{from \var{module} import *}}{(1)}
327\lineiii{__*__}{System-defined name}{}
328\lineiii{__*}{Class-private name mangling}{}
329\end{tableiii}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000330
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000331See sections: \ref{import}, ``The \keyword{import} statement'';
332\ref{specialnames}, ``Special method names'';
333\ref{atom-identifiers}, ``Identifiers (Names)''.
Fred Drakef6669171998-05-06 19:52:49 +0000334
Fred Drake39fc1bc1999-03-05 18:30:21 +0000335Note:
336
337\begin{description}
338\item[(1)] The special identifier \samp{_} is used in the interactive
339interpreter to store the result of the last evaluation; it is stored
340in the \module{__builtin__} module. When not in interactive mode,
341\samp{_} has no special meaning and is not defined.
342\end{description}
343
344
Fred Drake61c77281998-07-28 19:34:22 +0000345\section{Literals\label{literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000346
347Literals are notations for constant values of some built-in types.
348\index{literal}
349\index{constant}
350
Fred Drakef5eae662001-06-23 05:26:52 +0000351
Fred Drake61c77281998-07-28 19:34:22 +0000352\subsection{String literals\label{strings}}
Fred Drakef6669171998-05-06 19:52:49 +0000353
354String literals are described by the following lexical definitions:
355\index{string literal}
356
Fred Drakec37b65e2001-11-28 07:26:15 +0000357\index{ASCII@\ASCII}
Fred Drakecb4638a2001-07-06 22:49:53 +0000358\begin{productionlist}
359 \production{stringliteral}
Fred Drakec0cf7262001-08-14 21:43:31 +0000360 {[\token{stringprefix}](\token{shortstring} | \token{longstring})}
361 \production{stringprefix}
362 {"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000363 \production{shortstring}
364 {"'" \token{shortstringitem}* "'"
365 | '"' \token{shortstringitem}* '"'}
366 \production{longstring}
Fred Drake53815882002-03-15 23:21:37 +0000367 {"'''" \token{longstringitem}* "'''"}
368 \productioncont{| '"""' \token{longstringitem}* '"""'}
Fred Drakecb4638a2001-07-06 22:49:53 +0000369 \production{shortstringitem}
370 {\token{shortstringchar} | \token{escapeseq}}
371 \production{longstringitem}
372 {\token{longstringchar} | \token{escapeseq}}
373 \production{shortstringchar}
374 {<any ASCII character except "\e" or newline or the quote>}
375 \production{longstringchar}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000376 {<any ASCII character except "\e">}
Fred Drakecb4638a2001-07-06 22:49:53 +0000377 \production{escapeseq}
378 {"\e" <any ASCII character>}
379\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000380
Fred Drakec0cf7262001-08-14 21:43:31 +0000381One syntactic restriction not indicated by these productions is that
382whitespace is not allowed between the \grammartoken{stringprefix} and
383the rest of the string literal.
384
Fred Drakedea764d2000-12-19 04:52:03 +0000385\index{triple-quoted string}
386\index{Unicode Consortium}
387\index{string!Unicode}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000388In plain English: String literals can be enclosed in matching single
389quotes (\code{'}) or double quotes (\code{"}). They can also be
390enclosed in matching groups of three single or double quotes (these
391are generally referred to as \emph{triple-quoted strings}). The
392backslash (\code{\e}) character is used to escape characters that
393otherwise have a special meaning, such as newline, backslash itself,
394or the quote character. String literals may optionally be prefixed
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000395with a letter \character{r} or \character{R}; such strings are called
396\dfn{raw strings}\index{raw string} and use different rules for interpreting
397backslash escape sequences. A prefix of \character{u} or \character{U}
398makes the string a Unicode string. Unicode strings use the Unicode character
399set as defined by the Unicode Consortium and ISO~10646. Some additional
Fred Drakedea764d2000-12-19 04:52:03 +0000400escape sequences, described below, are available in Unicode strings.
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000401The two prefix characters may be combined; in this case, \character{u} must
402appear before \character{r}.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000403
404In triple-quoted strings,
Fred Drakef6669171998-05-06 19:52:49 +0000405unescaped newlines and quotes are allowed (and are retained), except
406that three unescaped quotes in a row terminate the string. (A
407``quote'' is the character used to open the string, i.e. either
Fred Drake5c07d9b1998-05-14 19:37:06 +0000408\code{'} or \code{"}.)
Fred Drakef6669171998-05-06 19:52:49 +0000409
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000410Unless an \character{r} or \character{R} prefix is present, escape
411sequences in strings are interpreted according to rules similar
Fred Drake90791642001-07-20 15:33:23 +0000412to those used by Standard C. The recognized escape sequences are:
Fred Drakef6669171998-05-06 19:52:49 +0000413\index{physical line}
414\index{escape sequence}
415\index{Standard C}
416\index{C}
417
Fred Drake3e930ba2002-09-24 21:08:37 +0000418\begin{tableiii}{l|l|c}{code}{Escape Sequence}{Meaning}{Notes}
419\lineiii{\e\var{newline}} {Ignored}{}
420\lineiii{\e\e} {Backslash (\code{\e})}{}
421\lineiii{\e'} {Single quote (\code{'})}{}
422\lineiii{\e"} {Double quote (\code{"})}{}
423\lineiii{\e a} {\ASCII{} Bell (BEL)}{}
424\lineiii{\e b} {\ASCII{} Backspace (BS)}{}
425\lineiii{\e f} {\ASCII{} Formfeed (FF)}{}
426\lineiii{\e n} {\ASCII{} Linefeed (LF)}{}
427\lineiii{\e N\{\var{name}\}}
428 {Character named \var{name} in the Unicode database (Unicode only)}{}
429\lineiii{\e r} {\ASCII{} Carriage Return (CR)}{}
430\lineiii{\e t} {\ASCII{} Horizontal Tab (TAB)}{}
431\lineiii{\e u\var{xxxx}}
432 {Character with 16-bit hex value \var{xxxx} (Unicode only)}{(1)}
433\lineiii{\e U\var{xxxxxxxx}}
434 {Character with 32-bit hex value \var{xxxxxxxx} (Unicode only)}{(2)}
435\lineiii{\e v} {\ASCII{} Vertical Tab (VT)}{}
436\lineiii{\e\var{ooo}} {\ASCII{} character with octal value \var{ooo}}{(3)}
437\lineiii{\e x\var{hh}} {\ASCII{} character with hex value \var{hh}}{(4)}
438\end{tableiii}
Fred Drakec37b65e2001-11-28 07:26:15 +0000439\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000440
Fred Drake3e930ba2002-09-24 21:08:37 +0000441\noindent
442Notes:
443
444\begin{itemize}
445\item[(1)]
446 Individual code units which form parts of a surrogate pair can be
447 encoded using this escape sequence.
448\item[(2)]
449 Any Unicode character can be encoded this way, but characters
450 outside the Basic Multilingual Plane (BMP) will be encoded using a
451 surrogate pair if Python is compiled to use 16-bit code units (the
452 default). Individual code units which form parts of a surrogate
453 pair can be encoded using this escape sequence.
454\item[(3)]
455 As in Standard C, up to three octal digits are accepted.
456\item[(4)]
457 Unlike in Standard C, at most two hex digits are accepted.
458\end{itemize}
459
Fred Drakef6669171998-05-06 19:52:49 +0000460
Fred Drakedea764d2000-12-19 04:52:03 +0000461Unlike Standard \index{unrecognized escape sequence}C,
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000462all unrecognized escape sequences are left in the string unchanged,
Fred Drakedea764d2000-12-19 04:52:03 +0000463i.e., \emph{the backslash is left in the string}. (This behavior is
Fred Drakef6669171998-05-06 19:52:49 +0000464useful when debugging: if an escape sequence is mistyped, the
Fred Drakedea764d2000-12-19 04:52:03 +0000465resulting output is more easily recognized as broken.) It is also
466important to note that the escape sequences marked as ``(Unicode
467only)'' in the table above fall into the category of unrecognized
468escapes for non-Unicode string literals.
Fred Drakef6669171998-05-06 19:52:49 +0000469
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000470When an \character{r} or \character{R} prefix is present, a character
471following a backslash is included in the string without change, and \emph{all
Fred Drake347a6252001-01-09 21:38:16 +0000472backslashes are left in the string}. For example, the string literal
473\code{r"\e n"} consists of two characters: a backslash and a lowercase
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000474\character{n}. String quotes can be escaped with a backslash, but the
475backslash remains in the string; for example, \code{r"\e""} is a valid string
Fred Drake347a6252001-01-09 21:38:16 +0000476literal consisting of two characters: a backslash and a double quote;
Fred Drake0825dc22001-07-20 14:32:28 +0000477\code{r"\e"} is not a valid string literal (even a raw string cannot
Fred Drake347a6252001-01-09 21:38:16 +0000478end in an odd number of backslashes). Specifically, \emph{a raw
479string cannot end in a single backslash} (since the backslash would
480escape the following quote character). Note also that a single
481backslash followed by a newline is interpreted as those two characters
482as part of the string, \emph{not} as a line continuation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000483
Fred Drakef7aa1642002-08-07 13:24:09 +0000484When an \character{r} or \character{R} prefix is used in conjunction
485with a \character{u} or \character{U} prefix, then the \code{\e uXXXX}
486escape sequence is processed while \emph{all other backslashes are
Fred Drake3e930ba2002-09-24 21:08:37 +0000487left in the string}. For example, the string literal
488\code{ur"\e{}u0062\e n"} consists of three Unicode characters: `LATIN
489SMALL LETTER B', `REVERSE SOLIDUS', and `LATIN SMALL LETTER N'.
490Backslashes can be escaped with a preceding backslash; however, both
491remain in the string. As a result, \code{\e uXXXX} escape sequences
492are only recognized when there are an odd number of backslashes.
Fred Drakef5eae662001-06-23 05:26:52 +0000493
Fred Drake61c77281998-07-28 19:34:22 +0000494\subsection{String literal concatenation\label{string-catenation}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000495
496Multiple adjacent string literals (delimited by whitespace), possibly
497using different quoting conventions, are allowed, and their meaning is
498the same as their concatenation. Thus, \code{"hello" 'world'} is
499equivalent to \code{"helloworld"}. This feature can be used to reduce
500the number of backslashes needed, to split long strings conveniently
501across long lines, or even to add comments to parts of strings, for
502example:
503
504\begin{verbatim}
505re.compile("[A-Za-z_]" # letter or underscore
506 "[A-Za-z0-9_]*" # letter, digit or underscore
507 )
508\end{verbatim}
509
510Note that this feature is defined at the syntactical level, but
511implemented at compile time. The `+' operator must be used to
512concatenate string expressions at run time. Also note that literal
513concatenation can use different quoting styles for each component
514(even mixing raw strings and triple quoted strings).
515
Fred Drake2ed27d32000-11-17 19:05:12 +0000516
Fred Drake61c77281998-07-28 19:34:22 +0000517\subsection{Numeric literals\label{numbers}}
Fred Drakef6669171998-05-06 19:52:49 +0000518
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000519There are four types of numeric literals: plain integers, long
520integers, floating point numbers, and imaginary numbers. There are no
521complex literals (complex numbers can be formed by adding a real
522number and an imaginary number).
Fred Drakef6669171998-05-06 19:52:49 +0000523\index{number}
524\index{numeric literal}
525\index{integer literal}
526\index{plain integer literal}
527\index{long integer literal}
528\index{floating point literal}
529\index{hexadecimal literal}
530\index{octal literal}
531\index{decimal literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000532\index{imaginary literal}
Fred Drakeed9e4532002-04-23 20:04:46 +0000533\index{complex!literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000534
535Note that numeric literals do not include a sign; a phrase like
536\code{-1} is actually an expression composed of the unary operator
537`\code{-}' and the literal \code{1}.
538
Fred Drakef5eae662001-06-23 05:26:52 +0000539
Fred Drake61c77281998-07-28 19:34:22 +0000540\subsection{Integer and long integer literals\label{integers}}
Fred Drakef6669171998-05-06 19:52:49 +0000541
542Integer and long integer literals are described by the following
543lexical definitions:
544
Fred Drakecb4638a2001-07-06 22:49:53 +0000545\begin{productionlist}
546 \production{longinteger}
547 {\token{integer} ("l" | "L")}
548 \production{integer}
549 {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
550 \production{decimalinteger}
551 {\token{nonzerodigit} \token{digit}* | "0"}
552 \production{octinteger}
553 {"0" \token{octdigit}+}
554 \production{hexinteger}
555 {"0" ("x" | "X") \token{hexdigit}+}
556 \production{nonzerodigit}
557 {"1"..."9"}
558 \production{octdigit}
559 {"0"..."7"}
560 \production{hexdigit}
561 {\token{digit} | "a"..."f" | "A"..."F"}
562\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000563
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000564Although both lower case \character{l} and upper case \character{L} are
565allowed as suffix for long integers, it is strongly recommended to always
566use \character{L}, since the letter \character{l} looks too much like the
567digit \character{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000568
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000569Plain integer decimal literals that are above the largest representable
570plain integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
571as if they were long integers instead. Octal and hexadecimal literals
572behave similarly, but when in the range just above the largest representable
573plain integer but below the largest unsigned 32-bit number (on a machine
574using 32-bit arithmetic), 4294967296, they are taken as the negative plain
575integer obtained by subtracting 4294967296 from their unsigned value. There
576is no limit for long integer literals apart from what can be stored in
577available memory. For example, 0xdeadbeef is taken, on a 32-bit machine,
578as the value -559038737, while 0xdeadbeeffeed is taken as the value
579244837814107885L.
Fred Drakef6669171998-05-06 19:52:49 +0000580
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000581Some examples of plain integer literals (first row) and long integer
582literals (second and third rows):
Fred Drakef6669171998-05-06 19:52:49 +0000583
584\begin{verbatim}
5857 2147483647 0177 0x80000000
5863L 79228162514264337593543950336L 0377L 0x100000000L
Raymond Hettingere701dcb2003-01-19 13:08:18 +0000587 79228162514264337593543950336 0xdeadbeeffeed
Fred Drakef6669171998-05-06 19:52:49 +0000588\end{verbatim}
589
Fred Drakef5eae662001-06-23 05:26:52 +0000590
Fred Drake61c77281998-07-28 19:34:22 +0000591\subsection{Floating point literals\label{floating}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000592
Fred Drakef6669171998-05-06 19:52:49 +0000593Floating point literals are described by the following lexical
594definitions:
595
Fred Drakecb4638a2001-07-06 22:49:53 +0000596\begin{productionlist}
597 \production{floatnumber}
598 {\token{pointfloat} | \token{exponentfloat}}
599 \production{pointfloat}
600 {[\token{intpart}] \token{fraction} | \token{intpart} "."}
601 \production{exponentfloat}
Tim Petersd507dab2001-08-30 20:51:59 +0000602 {(\token{intpart} | \token{pointfloat})
Fred Drakecb4638a2001-07-06 22:49:53 +0000603 \token{exponent}}
604 \production{intpart}
Tim Petersd507dab2001-08-30 20:51:59 +0000605 {\token{digit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000606 \production{fraction}
607 {"." \token{digit}+}
608 \production{exponent}
609 {("e" | "E") ["+" | "-"] \token{digit}+}
610\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000611
Tim Petersd507dab2001-08-30 20:51:59 +0000612Note that the integer and exponent parts of floating point numbers
613can look like octal integers, but are interpreted using radix 10. For
614example, \samp{077e010} is legal, and denotes the same number
615as \samp{77e10}.
Fred Drakef6669171998-05-06 19:52:49 +0000616The allowed range of floating point literals is
617implementation-dependent.
Fred Drakef6669171998-05-06 19:52:49 +0000618Some examples of floating point literals:
619
620\begin{verbatim}
Tim Petersd507dab2001-08-30 20:51:59 +00006213.14 10. .001 1e100 3.14e-10 0e0
Fred Drakef6669171998-05-06 19:52:49 +0000622\end{verbatim}
623
624Note that numeric literals do not include a sign; a phrase like
Fred Drake5c07d9b1998-05-14 19:37:06 +0000625\code{-1} is actually an expression composed of the operator
626\code{-} and the literal \code{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000627
Fred Drakef5eae662001-06-23 05:26:52 +0000628
Fred Drake61c77281998-07-28 19:34:22 +0000629\subsection{Imaginary literals\label{imaginary}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000630
631Imaginary literals are described by the following lexical definitions:
632
Fred Drakecb4638a2001-07-06 22:49:53 +0000633\begin{productionlist}
634 \production{imagnumber}{(\token{floatnumber} | \token{intpart}) ("j" | "J")}
635\end{productionlist}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000636
Fred Drakee15956b2000-04-03 04:51:13 +0000637An imaginary literal yields a complex number with a real part of
Guido van Rossum60f2f0c1998-06-15 18:00:50 +00006380.0. Complex numbers are represented as a pair of floating point
639numbers and have the same restrictions on their range. To create a
640complex number with a nonzero real part, add a floating point number
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000641to it, e.g., \code{(3+4j)}. Some examples of imaginary literals:
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000642
643\begin{verbatim}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00006443.14j 10.j 10j .001j 1e100j 3.14e-10j
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000645\end{verbatim}
646
647
Fred Drake61c77281998-07-28 19:34:22 +0000648\section{Operators\label{operators}}
Fred Drakef6669171998-05-06 19:52:49 +0000649
650The following tokens are operators:
651\index{operators}
652
653\begin{verbatim}
Fred Drakea7d608d2001-08-08 05:37:21 +0000654+ - * ** / // %
Fred Drakef6669171998-05-06 19:52:49 +0000655<< >> & | ^ ~
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000656< > <= >= == != <>
Fred Drakef6669171998-05-06 19:52:49 +0000657\end{verbatim}
658
Fred Drake5c07d9b1998-05-14 19:37:06 +0000659The comparison operators \code{<>} and \code{!=} are alternate
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000660spellings of the same operator. \code{!=} is the preferred spelling;
661\code{<>} is obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000662
Fred Drakef5eae662001-06-23 05:26:52 +0000663
Fred Drake61c77281998-07-28 19:34:22 +0000664\section{Delimiters\label{delimiters}}
Fred Drakef6669171998-05-06 19:52:49 +0000665
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000666The following tokens serve as delimiters in the grammar:
Fred Drakef6669171998-05-06 19:52:49 +0000667\index{delimiters}
668
669\begin{verbatim}
670( ) [ ] { }
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000671, : . ` = ;
Fred Drakea7d608d2001-08-08 05:37:21 +0000672+= -= *= /= //= %=
673&= |= ^= >>= <<= **=
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000674\end{verbatim}
675
676The period can also occur in floating-point and imaginary literals. A
Fred Drakee15956b2000-04-03 04:51:13 +0000677sequence of three periods has a special meaning as an ellipsis in slices.
Thomas Wouters12bba852000-08-24 20:06:04 +0000678The second half of the list, the augmented assignment operators, serve
679lexically as delimiters, but also perform an operation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000680
Fred Drakec37b65e2001-11-28 07:26:15 +0000681The following printing \ASCII{} characters have special meaning as part
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000682of other tokens or are otherwise significant to the lexical analyzer:
683
684\begin{verbatim}
685' " # \
Fred Drakef6669171998-05-06 19:52:49 +0000686\end{verbatim}
687
688The following printing \ASCII{} characters are not used in Python. Their
689occurrence outside string literals and comments is an unconditional
690error:
Fred Drakec37b65e2001-11-28 07:26:15 +0000691\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000692
693\begin{verbatim}
694@ $ ?
695\end{verbatim}