blob: 7b70676f622863e58cf2933abe9ebae79a63deda [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
Georg Brandla635fbb2006-01-15 07:55:35 +000012string literals and comments use an encoding different from ASCII]{2.3}
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000013For 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
Fred Drakedb229582005-05-25 05:29:17 +000057A physical line is a sequence of characters terminated by an end-of-line
58sequence. In source files, any of the standard platform line
Thomas Wouters0e3f5912006-08-11 14:57:12 +000059termination sequences can be used - the \UNIX{} form using \ASCII{} LF
Fred Drakedb229582005-05-25 05:29:17 +000060(linefeed), the Windows form using the \ASCII{} sequence CR LF (return
61followed by linefeed), or the Macintosh form using the \ASCII{} CR
62(return) character. All of these forms can be used equally, regardless
63of platform.
64
65When embedding Python, source code strings should be passed to Python
66APIs using the standard C conventions for newline characters (the
67\code{\e n} character, representing \ASCII{} LF, is the line
68terminator).
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000069
Fred Drakef5eae662001-06-23 05:26:52 +000070
Fred Drake61c77281998-07-28 19:34:22 +000071\subsection{Comments\label{comments}}
Fred Drakef6669171998-05-06 19:52:49 +000072
Fred Drake5c07d9b1998-05-14 19:37:06 +000073A comment starts with a hash character (\code{\#}) that is not part of
Fred Drakef6669171998-05-06 19:52:49 +000074a string literal, and ends at the end of the physical line. A comment
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000075signifies the end of the logical line unless the implicit line joining
76rules are invoked.
77Comments are ignored by the syntax; they are not tokens.
Fred Drakef6669171998-05-06 19:52:49 +000078\index{comment}
Fred Drakef6669171998-05-06 19:52:49 +000079\index{hash character}
80
Fred Drakef5eae662001-06-23 05:26:52 +000081
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000082\subsection{Encoding declarations\label{encodings}}
Martin v. Löwis266a4362004-09-14 07:52:22 +000083\index{source character set}
84\index{encodings}
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000085
86If a comment in the first or second line of the Python script matches
Martin v. Löwisae075b62004-08-18 13:25:05 +000087the regular expression \regexp{coding[=:]\e s*([-\e w.]+)}, this comment is
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +000088processed as an encoding declaration; the first group of this
89expression names the encoding of the source code file. The recommended
90forms of this expression are
91
92\begin{verbatim}
93# -*- coding: <encoding-name> -*-
94\end{verbatim}
95
96which is recognized also by GNU Emacs, and
97
98\begin{verbatim}
99# vim:fileencoding=<encoding-name>
100\end{verbatim}
101
Raymond Hettinger3fd97792004-02-08 20:18:26 +0000102which is recognized by Bram Moolenaar's VIM. In addition, if the first
Fred Drake31f3db32002-08-06 21:36:06 +0000103bytes of the file are the UTF-8 byte-order mark
104(\code{'\e xef\e xbb\e xbf'}), the declared file encoding is UTF-8
105(this is supported, among others, by Microsoft's \program{notepad}).
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000106
107If an encoding is declared, the encoding name must be recognized by
108Python. % XXX there should be a list of supported encodings.
109The encoding is used for all lexical analysis, in particular to find
110the end of a string, and to interpret the contents of Unicode literals.
111String literals are converted to Unicode for syntactical analysis,
112then converted back to their original encoding before interpretation
Martin v. Löwisf62a89b2002-09-03 11:52:44 +0000113starts. The encoding declaration must appear on a line of its own.
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +0000114
Fred Drake61c77281998-07-28 19:34:22 +0000115\subsection{Explicit line joining\label{explicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000116
117Two or more physical lines may be joined into logical lines using
Fred Drake5c07d9b1998-05-14 19:37:06 +0000118backslash characters (\code{\e}), as follows: when a physical line ends
Fred Drakef6669171998-05-06 19:52:49 +0000119in a backslash that is not part of a string literal or comment, it is
120joined with the following forming a single logical line, deleting the
121backslash and the following end-of-line character. For example:
122\index{physical line}
123\index{line joining}
124\index{line continuation}
125\index{backslash character}
126%
127\begin{verbatim}
128if 1900 < year < 2100 and 1 <= month <= 12 \
129 and 1 <= day <= 31 and 0 <= hour < 24 \
130 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
131 return 1
132\end{verbatim}
133
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000134A line ending in a backslash cannot carry a comment. A backslash does
135not continue a comment. A backslash does not continue a token except
136for string literals (i.e., tokens other than string literals cannot be
137split across physical lines using a backslash). A backslash is
138illegal elsewhere on a line outside a string literal.
Fred Drakef6669171998-05-06 19:52:49 +0000139
Fred Drakec411fa61999-02-22 14:32:18 +0000140
Fred Drake61c77281998-07-28 19:34:22 +0000141\subsection{Implicit line joining\label{implicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +0000142
143Expressions in parentheses, square brackets or curly braces can be
144split over more than one physical line without using backslashes.
145For example:
146
147\begin{verbatim}
148month_names = ['Januari', 'Februari', 'Maart', # These are the
149 'April', 'Mei', 'Juni', # Dutch names
150 'Juli', 'Augustus', 'September', # for the months
151 'Oktober', 'November', 'December'] # of the year
152\end{verbatim}
153
154Implicitly continued lines can carry comments. The indentation of the
155continuation lines is not important. Blank continuation lines are
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000156allowed. There is no NEWLINE token between implicit continuation
157lines. Implicitly continued lines can also occur within triple-quoted
158strings (see below); in that case they cannot carry comments.
Fred Drakef6669171998-05-06 19:52:49 +0000159
Fred Drakef6669171998-05-06 19:52:49 +0000160
Fred Drake79713fd2002-10-24 19:57:37 +0000161\subsection{Blank lines \label{blank-lines}}
Fred Drakec411fa61999-02-22 14:32:18 +0000162
Fred Drake79713fd2002-10-24 19:57:37 +0000163\index{blank line}
Fred Drakec411fa61999-02-22 14:32:18 +0000164A logical line that contains only spaces, tabs, formfeeds and possibly
165a comment, is ignored (i.e., no NEWLINE token is generated). During
166interactive input of statements, handling of a blank line may differ
167depending on the implementation of the read-eval-print loop. In the
168standard implementation, an entirely blank logical line (i.e.\ one
169containing not even whitespace or a comment) terminates a multi-line
170statement.
171
Fred Drakef6669171998-05-06 19:52:49 +0000172
Fred Drake61c77281998-07-28 19:34:22 +0000173\subsection{Indentation\label{indentation}}
Fred Drakef6669171998-05-06 19:52:49 +0000174
175Leading whitespace (spaces and tabs) at the beginning of a logical
176line is used to compute the indentation level of the line, which in
177turn is used to determine the grouping of statements.
178\index{indentation}
179\index{whitespace}
180\index{leading whitespace}
181\index{space}
182\index{tab}
183\index{grouping}
184\index{statement grouping}
185
186First, tabs are replaced (from left to right) by one to eight spaces
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000187such that the total number of characters up to and including the
188replacement is a multiple of
Fred Drakec37b65e2001-11-28 07:26:15 +0000189eight (this is intended to be the same rule as used by \UNIX). The
Fred Drakef6669171998-05-06 19:52:49 +0000190total number of spaces preceding the first non-blank character then
191determines the line's indentation. Indentation cannot be split over
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000192multiple physical lines using backslashes; the whitespace up to the
193first backslash determines the indentation.
194
195\strong{Cross-platform compatibility note:} because of the nature of
196text editors on non-UNIX platforms, it is unwise to use a mixture of
Martin v. Löwis171be762003-06-21 13:40:02 +0000197spaces and tabs for the indentation in a single source file. It
198should also be noted that different platforms may explicitly limit the
199maximum indentation level.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000200
201A formfeed character may be present at the start of the line; it will
Fred Drakee15956b2000-04-03 04:51:13 +0000202be ignored for the indentation calculations above. Formfeed
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000203characters occurring elsewhere in the leading whitespace have an
204undefined effect (for instance, they may reset the space count to
205zero).
Fred Drakef6669171998-05-06 19:52:49 +0000206
207The indentation levels of consecutive lines are used to generate
208INDENT and DEDENT tokens, using a stack, as follows.
209\index{INDENT token}
210\index{DEDENT token}
211
212Before the first line of the file is read, a single zero is pushed on
213the stack; this will never be popped off again. The numbers pushed on
214the stack will always be strictly increasing from bottom to top. At
215the beginning of each logical line, the line's indentation level is
216compared to the top of the stack. If it is equal, nothing happens.
217If it is larger, it is pushed on the stack, and one INDENT token is
Fred Drake5c07d9b1998-05-14 19:37:06 +0000218generated. If it is smaller, it \emph{must} be one of the numbers
Fred Drakef6669171998-05-06 19:52:49 +0000219occurring on the stack; all numbers on the stack that are larger are
220popped off, and for each number popped off a DEDENT token is
221generated. At the end of the file, a DEDENT token is generated for
222each number remaining on the stack that is larger than zero.
223
224Here is an example of a correctly (though confusingly) indented piece
225of Python code:
226
227\begin{verbatim}
228def perm(l):
229 # Compute the list of all permutations of l
Fred Drakef6669171998-05-06 19:52:49 +0000230 if len(l) <= 1:
231 return [l]
232 r = []
233 for i in range(len(l)):
234 s = l[:i] + l[i+1:]
235 p = perm(s)
236 for x in p:
237 r.append(l[i:i+1] + x)
238 return r
239\end{verbatim}
240
241The following example shows various indentation errors:
242
243\begin{verbatim}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000244 def perm(l): # error: first line indented
245for i in range(len(l)): # error: not indented
246 s = l[:i] + l[i+1:]
247 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
248 for x in p:
249 r.append(l[i:i+1] + x)
250 return r # error: inconsistent dedent
Fred Drakef6669171998-05-06 19:52:49 +0000251\end{verbatim}
252
253(Actually, the first three errors are detected by the parser; only the
254last error is found by the lexical analyzer --- the indentation of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000255\code{return r} does not match a level popped off the stack.)
Fred Drakef6669171998-05-06 19:52:49 +0000256
Fred Drakef5eae662001-06-23 05:26:52 +0000257
Fred Drake61c77281998-07-28 19:34:22 +0000258\subsection{Whitespace between tokens\label{whitespace}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000259
260Except at the beginning of a logical line or in string literals, the
261whitespace characters space, tab and formfeed can be used
262interchangeably to separate tokens. Whitespace is needed between two
263tokens only if their concatenation could otherwise be interpreted as a
264different token (e.g., ab is one token, but a b is two tokens).
265
Fred Drakef5eae662001-06-23 05:26:52 +0000266
Fred Drake61c77281998-07-28 19:34:22 +0000267\section{Other tokens\label{other-tokens}}
Fred Drakef6669171998-05-06 19:52:49 +0000268
269Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000270exist: \emph{identifiers}, \emph{keywords}, \emph{literals},
271\emph{operators}, and \emph{delimiters}.
272Whitespace characters (other than line terminators, discussed earlier)
273are not tokens, but serve to delimit tokens.
274Where
Fred Drakef6669171998-05-06 19:52:49 +0000275ambiguity exists, a token comprises the longest possible string that
276forms a legal token, when read from left to right.
277
Fred Drakef5eae662001-06-23 05:26:52 +0000278
Fred Drake61c77281998-07-28 19:34:22 +0000279\section{Identifiers and keywords\label{identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +0000280
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000281Identifiers (also referred to as \emph{names}) are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000282lexical definitions:
283\index{identifier}
284\index{name}
285
Fred Drakecb4638a2001-07-06 22:49:53 +0000286\begin{productionlist}
287 \production{identifier}
288 {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
289 \production{letter}
290 {\token{lowercase} | \token{uppercase}}
291 \production{lowercase}
292 {"a"..."z"}
293 \production{uppercase}
294 {"A"..."Z"}
295 \production{digit}
296 {"0"..."9"}
297\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000298
299Identifiers are unlimited in length. Case is significant.
300
Fred Drakef5eae662001-06-23 05:26:52 +0000301
Fred Drake61c77281998-07-28 19:34:22 +0000302\subsection{Keywords\label{keywords}}
Fred Drakef6669171998-05-06 19:52:49 +0000303
Fred Drake5c07d9b1998-05-14 19:37:06 +0000304The following identifiers are used as reserved words, or
305\emph{keywords} of the language, and cannot be used as ordinary
306identifiers. They must be spelled exactly as written here:%
307\index{keyword}%
Fred Drakef6669171998-05-06 19:52:49 +0000308\index{reserved word}
309
310\begin{verbatim}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000311and def for is raise
312as del from lambda return
313assert elif global not try
314break else if or while
315class except import pass with
316continue finally in print yield
Fred Drakef6669171998-05-06 19:52:49 +0000317\end{verbatim}
318
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000319% When adding keywords, use reswords.py for reformatting
320
Thomas Wouters477c8d52006-05-27 19:21:47 +0000321\versionchanged[\constant{None} became a constant and is now
322recognized by the compiler as a name for the built-in object
323\constant{None}. Although it is not a keyword, you cannot assign
324a different object to it]{2.4}
Fred Drakea23b5732002-06-18 19:17:14 +0000325
Thomas Wouters477c8d52006-05-27 19:21:47 +0000326\versionchanged[Both \keyword{as} and \keyword{with} are only recognized
327when the \code{with_statement} future feature has been enabled.
328It will always be enabled in Python 2.6. See section~\ref{with} for
329details. Note that using \keyword{as} and \keyword{with} as identifiers
330will always issue a warning, even when the \code{with_statement} future
331directive is not in effect]{2.5}
Fred Drakea23b5732002-06-18 19:17:14 +0000332
Fred Drakef5eae662001-06-23 05:26:52 +0000333
Fred Drake61c77281998-07-28 19:34:22 +0000334\subsection{Reserved classes of identifiers\label{id-classes}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000335
336Certain classes of identifiers (besides keywords) have special
Fred Drake38f6b882003-09-06 03:50:07 +0000337meanings. These classes are identified by the patterns of leading and
338trailing underscore characters:
Fred Drake39fc1bc1999-03-05 18:30:21 +0000339
340\begin{description}
Fred Drake38f6b882003-09-06 03:50:07 +0000341
342\item[\code{_*}]
343 Not imported by \samp{from \var{module} import *}. The special
344 identifier \samp{_} is used in the interactive interpreter to store
345 the result of the last evaluation; it is stored in the
346 \module{__builtin__} module. When not in interactive mode, \samp{_}
347 has no special meaning and is not defined.
348 See section~\ref{import}, ``The \keyword{import} statement.''
349
350 \note{The name \samp{_} is often used in conjunction with
351 internationalization; refer to the documentation for the
352 \ulink{\module{gettext} module}{../lib/module-gettext.html} for more
353 information on this convention.}
354
355\item[\code{__*__}]
356 System-defined names. These names are defined by the interpreter
Neil Schemenauerc4932292005-06-18 17:54:13 +0000357 and its implementation (including the standard library);
Fred Drake38f6b882003-09-06 03:50:07 +0000358 applications should not expect to define additional names using this
359 convention. The set of names of this class defined by Python may be
360 extended in future versions.
361 See section~\ref{specialnames}, ``Special method names.''
362
363\item[\code{__*}]
364 Class-private names. Names in this category, when used within the
Martin v. Löwis13ff1162004-06-02 12:48:20 +0000365 context of a class definition, are re-written to use a mangled form
Fred Drake38f6b882003-09-06 03:50:07 +0000366 to help avoid name clashes between ``private'' attributes of base
367 and derived classes.
368 See section~\ref{atom-identifiers}, ``Identifiers (Names).''
369
Fred Drake39fc1bc1999-03-05 18:30:21 +0000370\end{description}
371
372
Fred Drake61c77281998-07-28 19:34:22 +0000373\section{Literals\label{literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000374
375Literals are notations for constant values of some built-in types.
376\index{literal}
377\index{constant}
378
Fred Drakef5eae662001-06-23 05:26:52 +0000379
Fred Drake61c77281998-07-28 19:34:22 +0000380\subsection{String literals\label{strings}}
Fred Drakef6669171998-05-06 19:52:49 +0000381
382String literals are described by the following lexical definitions:
383\index{string literal}
384
Fred Drakec37b65e2001-11-28 07:26:15 +0000385\index{ASCII@\ASCII}
Fred Drakecb4638a2001-07-06 22:49:53 +0000386\begin{productionlist}
387 \production{stringliteral}
Fred Drakec0cf7262001-08-14 21:43:31 +0000388 {[\token{stringprefix}](\token{shortstring} | \token{longstring})}
389 \production{stringprefix}
390 {"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000391 \production{shortstring}
392 {"'" \token{shortstringitem}* "'"
393 | '"' \token{shortstringitem}* '"'}
394 \production{longstring}
Fred Drake53815882002-03-15 23:21:37 +0000395 {"'''" \token{longstringitem}* "'''"}
396 \productioncont{| '"""' \token{longstringitem}* '"""'}
Fred Drakecb4638a2001-07-06 22:49:53 +0000397 \production{shortstringitem}
398 {\token{shortstringchar} | \token{escapeseq}}
399 \production{longstringitem}
400 {\token{longstringchar} | \token{escapeseq}}
401 \production{shortstringchar}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000402 {<any source character except "\e" or newline or the quote>}
Fred Drakecb4638a2001-07-06 22:49:53 +0000403 \production{longstringchar}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000404 {<any source character except "\e">}
Fred Drakecb4638a2001-07-06 22:49:53 +0000405 \production{escapeseq}
406 {"\e" <any ASCII character>}
407\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000408
Fred Drakec0cf7262001-08-14 21:43:31 +0000409One syntactic restriction not indicated by these productions is that
410whitespace is not allowed between the \grammartoken{stringprefix} and
Martin v. Löwis266a4362004-09-14 07:52:22 +0000411the rest of the string literal. The source character set is defined
Fred Drake5b000592004-11-10 16:51:17 +0000412by the encoding declaration; it is \ASCII{} if no encoding declaration
413is given in the source file; see section~\ref{encodings}.
Fred Drakec0cf7262001-08-14 21:43:31 +0000414
Fred Drakedea764d2000-12-19 04:52:03 +0000415\index{triple-quoted string}
416\index{Unicode Consortium}
417\index{string!Unicode}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000418In plain English: String literals can be enclosed in matching single
419quotes (\code{'}) or double quotes (\code{"}). They can also be
420enclosed in matching groups of three single or double quotes (these
421are generally referred to as \emph{triple-quoted strings}). The
422backslash (\code{\e}) character is used to escape characters that
423otherwise have a special meaning, such as newline, backslash itself,
424or the quote character. String literals may optionally be prefixed
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000425with a letter \character{r} or \character{R}; such strings are called
426\dfn{raw strings}\index{raw string} and use different rules for interpreting
427backslash escape sequences. A prefix of \character{u} or \character{U}
428makes the string a Unicode string. Unicode strings use the Unicode character
429set as defined by the Unicode Consortium and ISO~10646. Some additional
Fred Drakedea764d2000-12-19 04:52:03 +0000430escape sequences, described below, are available in Unicode strings.
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000431The two prefix characters may be combined; in this case, \character{u} must
432appear before \character{r}.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000433
434In triple-quoted strings,
Fred Drakef6669171998-05-06 19:52:49 +0000435unescaped newlines and quotes are allowed (and are retained), except
436that three unescaped quotes in a row terminate the string. (A
437``quote'' is the character used to open the string, i.e. either
Fred Drake5c07d9b1998-05-14 19:37:06 +0000438\code{'} or \code{"}.)
Fred Drakef6669171998-05-06 19:52:49 +0000439
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000440Unless an \character{r} or \character{R} prefix is present, escape
441sequences in strings are interpreted according to rules similar
Fred Drake90791642001-07-20 15:33:23 +0000442to those used by Standard C. The recognized escape sequences are:
Fred Drakef6669171998-05-06 19:52:49 +0000443\index{physical line}
444\index{escape sequence}
445\index{Standard C}
446\index{C}
447
Fred Drake3e930ba2002-09-24 21:08:37 +0000448\begin{tableiii}{l|l|c}{code}{Escape Sequence}{Meaning}{Notes}
449\lineiii{\e\var{newline}} {Ignored}{}
450\lineiii{\e\e} {Backslash (\code{\e})}{}
451\lineiii{\e'} {Single quote (\code{'})}{}
452\lineiii{\e"} {Double quote (\code{"})}{}
453\lineiii{\e a} {\ASCII{} Bell (BEL)}{}
454\lineiii{\e b} {\ASCII{} Backspace (BS)}{}
455\lineiii{\e f} {\ASCII{} Formfeed (FF)}{}
456\lineiii{\e n} {\ASCII{} Linefeed (LF)}{}
457\lineiii{\e N\{\var{name}\}}
458 {Character named \var{name} in the Unicode database (Unicode only)}{}
459\lineiii{\e r} {\ASCII{} Carriage Return (CR)}{}
460\lineiii{\e t} {\ASCII{} Horizontal Tab (TAB)}{}
461\lineiii{\e u\var{xxxx}}
462 {Character with 16-bit hex value \var{xxxx} (Unicode only)}{(1)}
463\lineiii{\e U\var{xxxxxxxx}}
464 {Character with 32-bit hex value \var{xxxxxxxx} (Unicode only)}{(2)}
465\lineiii{\e v} {\ASCII{} Vertical Tab (VT)}{}
Martin v. Löwis266a4362004-09-14 07:52:22 +0000466\lineiii{\e\var{ooo}} {Character with octal value \var{ooo}}{(3,5)}
467\lineiii{\e x\var{hh}} {Character with hex value \var{hh}}{(4,5)}
Fred Drake3e930ba2002-09-24 21:08:37 +0000468\end{tableiii}
Fred Drakec37b65e2001-11-28 07:26:15 +0000469\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000470
Fred Drake3e930ba2002-09-24 21:08:37 +0000471\noindent
472Notes:
473
474\begin{itemize}
475\item[(1)]
476 Individual code units which form parts of a surrogate pair can be
477 encoded using this escape sequence.
478\item[(2)]
479 Any Unicode character can be encoded this way, but characters
480 outside the Basic Multilingual Plane (BMP) will be encoded using a
481 surrogate pair if Python is compiled to use 16-bit code units (the
482 default). Individual code units which form parts of a surrogate
483 pair can be encoded using this escape sequence.
484\item[(3)]
485 As in Standard C, up to three octal digits are accepted.
486\item[(4)]
487 Unlike in Standard C, at most two hex digits are accepted.
Martin v. Löwis266a4362004-09-14 07:52:22 +0000488\item[(5)]
489 In a string literal, hexadecimal and octal escapes denote the
490 byte with the given value; it is not necessary that the byte
491 encodes a character in the source character set. In a Unicode
492 literal, these escapes denote a Unicode character with the given
493 value.
Fred Drake3e930ba2002-09-24 21:08:37 +0000494\end{itemize}
495
Fred Drakef6669171998-05-06 19:52:49 +0000496
Fred Drakedea764d2000-12-19 04:52:03 +0000497Unlike Standard \index{unrecognized escape sequence}C,
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000498all unrecognized escape sequences are left in the string unchanged,
Fred Drakedea764d2000-12-19 04:52:03 +0000499i.e., \emph{the backslash is left in the string}. (This behavior is
Fred Drakef6669171998-05-06 19:52:49 +0000500useful when debugging: if an escape sequence is mistyped, the
Fred Drakedea764d2000-12-19 04:52:03 +0000501resulting output is more easily recognized as broken.) It is also
502important to note that the escape sequences marked as ``(Unicode
503only)'' in the table above fall into the category of unrecognized
504escapes for non-Unicode string literals.
Fred Drakef6669171998-05-06 19:52:49 +0000505
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000506When an \character{r} or \character{R} prefix is present, a character
507following a backslash is included in the string without change, and \emph{all
Fred Drake347a6252001-01-09 21:38:16 +0000508backslashes are left in the string}. For example, the string literal
509\code{r"\e n"} consists of two characters: a backslash and a lowercase
Raymond Hettinger83dcf5a2002-08-07 16:53:17 +0000510\character{n}. String quotes can be escaped with a backslash, but the
511backslash remains in the string; for example, \code{r"\e""} is a valid string
Fred Drake347a6252001-01-09 21:38:16 +0000512literal consisting of two characters: a backslash and a double quote;
Fred Drake0825dc22001-07-20 14:32:28 +0000513\code{r"\e"} is not a valid string literal (even a raw string cannot
Fred Drake347a6252001-01-09 21:38:16 +0000514end in an odd number of backslashes). Specifically, \emph{a raw
515string cannot end in a single backslash} (since the backslash would
516escape the following quote character). Note also that a single
517backslash followed by a newline is interpreted as those two characters
518as part of the string, \emph{not} as a line continuation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000519
Fred Drakef7aa1642002-08-07 13:24:09 +0000520When an \character{r} or \character{R} prefix is used in conjunction
521with a \character{u} or \character{U} prefix, then the \code{\e uXXXX}
Georg Brandlf96f5f52005-11-22 19:23:58 +0000522and \code{\e UXXXXXXXX} escape sequences are processed while
523\emph{all other backslashes are left in the string}.
524For example, the string literal
Fred Drake3e930ba2002-09-24 21:08:37 +0000525\code{ur"\e{}u0062\e n"} consists of three Unicode characters: `LATIN
526SMALL LETTER B', `REVERSE SOLIDUS', and `LATIN SMALL LETTER N'.
527Backslashes can be escaped with a preceding backslash; however, both
528remain in the string. As a result, \code{\e uXXXX} escape sequences
529are only recognized when there are an odd number of backslashes.
Fred Drakef5eae662001-06-23 05:26:52 +0000530
Fred Drake61c77281998-07-28 19:34:22 +0000531\subsection{String literal concatenation\label{string-catenation}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000532
533Multiple adjacent string literals (delimited by whitespace), possibly
534using different quoting conventions, are allowed, and their meaning is
535the same as their concatenation. Thus, \code{"hello" 'world'} is
536equivalent to \code{"helloworld"}. This feature can be used to reduce
537the number of backslashes needed, to split long strings conveniently
538across long lines, or even to add comments to parts of strings, for
539example:
540
541\begin{verbatim}
542re.compile("[A-Za-z_]" # letter or underscore
543 "[A-Za-z0-9_]*" # letter, digit or underscore
544 )
545\end{verbatim}
546
547Note that this feature is defined at the syntactical level, but
548implemented at compile time. The `+' operator must be used to
549concatenate string expressions at run time. Also note that literal
550concatenation can use different quoting styles for each component
551(even mixing raw strings and triple quoted strings).
552
Fred Drake2ed27d32000-11-17 19:05:12 +0000553
Fred Drake61c77281998-07-28 19:34:22 +0000554\subsection{Numeric literals\label{numbers}}
Fred Drakef6669171998-05-06 19:52:49 +0000555
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000556There are four types of numeric literals: plain integers, long
557integers, floating point numbers, and imaginary numbers. There are no
558complex literals (complex numbers can be formed by adding a real
559number and an imaginary number).
Fred Drakef6669171998-05-06 19:52:49 +0000560\index{number}
561\index{numeric literal}
562\index{integer literal}
563\index{plain integer literal}
564\index{long integer literal}
565\index{floating point literal}
566\index{hexadecimal literal}
567\index{octal literal}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000568\index{binary literal}
Fred Drakef6669171998-05-06 19:52:49 +0000569\index{decimal literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000570\index{imaginary literal}
Fred Drakeed9e4532002-04-23 20:04:46 +0000571\index{complex!literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000572
573Note that numeric literals do not include a sign; a phrase like
574\code{-1} is actually an expression composed of the unary operator
575`\code{-}' and the literal \code{1}.
576
Fred Drakef5eae662001-06-23 05:26:52 +0000577
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000578\subsection{Integer literals\label{integers}}
Fred Drakef6669171998-05-06 19:52:49 +0000579
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000580Integer literals are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000581lexical definitions:
582
Fred Drakecb4638a2001-07-06 22:49:53 +0000583\begin{productionlist}
Fred Drakecb4638a2001-07-06 22:49:53 +0000584 \production{integer}
585 {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
586 \production{decimalinteger}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000587 {\token{nonzerodigit} \token{digit}* | "0"+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000588 \production{octinteger}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000589 {"0" ("o" | "O") \token{octdigit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000590 \production{hexinteger}
591 {"0" ("x" | "X") \token{hexdigit}+}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000592 \production{bininteger}
593 {"0" ("b" | "B") \token{bindigit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000594 \production{nonzerodigit}
595 {"1"..."9"}
596 \production{octdigit}
597 {"0"..."7"}
598 \production{hexdigit}
599 {\token{digit} | "a"..."f" | "A"..."F"}
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000600 \production{bindigit}
601 {"0"..."1"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000602\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000603
Guido van Rossum6c9e1302003-11-29 23:52:13 +0000604Plain integer literals that are above the largest representable plain
605integer (e.g., 2147483647 when using 32-bit arithmetic) are accepted
606as if they were long integers instead.\footnote{In versions of Python
607prior to 2.4, octal and hexadecimal literals in the range just above
608the largest representable plain integer but below the largest unsigned
60932-bit number (on a machine using 32-bit arithmetic), 4294967296, were
610taken as the negative plain integer obtained by subtracting 4294967296
611from their unsigned value.} There is no limit for long integer
612literals apart from what can be stored in available memory.
Fred Drakef6669171998-05-06 19:52:49 +0000613
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000614Note that leading zeros in a non-zero decimal number are not allowed.
615This is for disambiguation with C-style octal literals, which Python
616used before version 3.0.
617
618Some examples of integer literals:
Fred Drakef6669171998-05-06 19:52:49 +0000619
620\begin{verbatim}
Guido van Rossumcd16bf62007-06-13 18:07:49 +00006217 2147483647 0o177 0b100110111
6223 79228162514264337593543950336 0o377 0x100000000
623 79228162514264337593543950336 0xdeadbeef
Fred Drakef6669171998-05-06 19:52:49 +0000624\end{verbatim}
625
Fred Drakef5eae662001-06-23 05:26:52 +0000626
Fred Drake61c77281998-07-28 19:34:22 +0000627\subsection{Floating point literals\label{floating}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000628
Fred Drakef6669171998-05-06 19:52:49 +0000629Floating point literals are described by the following lexical
630definitions:
631
Fred Drakecb4638a2001-07-06 22:49:53 +0000632\begin{productionlist}
633 \production{floatnumber}
634 {\token{pointfloat} | \token{exponentfloat}}
635 \production{pointfloat}
636 {[\token{intpart}] \token{fraction} | \token{intpart} "."}
637 \production{exponentfloat}
Tim Petersd507dab2001-08-30 20:51:59 +0000638 {(\token{intpart} | \token{pointfloat})
Fred Drakecb4638a2001-07-06 22:49:53 +0000639 \token{exponent}}
640 \production{intpart}
Tim Petersd507dab2001-08-30 20:51:59 +0000641 {\token{digit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000642 \production{fraction}
643 {"." \token{digit}+}
644 \production{exponent}
645 {("e" | "E") ["+" | "-"] \token{digit}+}
646\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000647
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000648Note that the integer and exponent parts are always interpreted using
649radix 10. For example, \samp{077e010} is legal, and denotes the same
650number as \samp{77e10}.
651The allowed range of floating point literals is implementation-dependent.
Fred Drakef6669171998-05-06 19:52:49 +0000652Some examples of floating point literals:
653
654\begin{verbatim}
Tim Petersd507dab2001-08-30 20:51:59 +00006553.14 10. .001 1e100 3.14e-10 0e0
Fred Drakef6669171998-05-06 19:52:49 +0000656\end{verbatim}
657
658Note that numeric literals do not include a sign; a phrase like
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659\code{-1} is actually an expression composed of the unary operator
Fred Drake5c07d9b1998-05-14 19:37:06 +0000660\code{-} and the literal \code{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000661
Fred Drakef5eae662001-06-23 05:26:52 +0000662
Fred Drake61c77281998-07-28 19:34:22 +0000663\subsection{Imaginary literals\label{imaginary}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000664
665Imaginary literals are described by the following lexical definitions:
666
Fred Drakecb4638a2001-07-06 22:49:53 +0000667\begin{productionlist}
668 \production{imagnumber}{(\token{floatnumber} | \token{intpart}) ("j" | "J")}
669\end{productionlist}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000670
Fred Drakee15956b2000-04-03 04:51:13 +0000671An imaginary literal yields a complex number with a real part of
Guido van Rossum60f2f0c1998-06-15 18:00:50 +00006720.0. Complex numbers are represented as a pair of floating point
673numbers and have the same restrictions on their range. To create a
674complex number with a nonzero real part, add a floating point number
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000675to it, e.g., \code{(3+4j)}. Some examples of imaginary literals:
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000676
677\begin{verbatim}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00006783.14j 10.j 10j .001j 1e100j 3.14e-10j
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000679\end{verbatim}
680
681
Fred Drake61c77281998-07-28 19:34:22 +0000682\section{Operators\label{operators}}
Fred Drakef6669171998-05-06 19:52:49 +0000683
684The following tokens are operators:
685\index{operators}
686
687\begin{verbatim}
Fred Drakea7d608d2001-08-08 05:37:21 +0000688+ - * ** / // %
Fred Drakef6669171998-05-06 19:52:49 +0000689<< >> & | ^ ~
Neal Norwitz3bd844e2006-08-29 04:39:12 +0000690< > <= >= == !=
Fred Drakef6669171998-05-06 19:52:49 +0000691\end{verbatim}
692
Fred Drakef5eae662001-06-23 05:26:52 +0000693
Fred Drake61c77281998-07-28 19:34:22 +0000694\section{Delimiters\label{delimiters}}
Fred Drakef6669171998-05-06 19:52:49 +0000695
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000696The following tokens serve as delimiters in the grammar:
Fred Drakef6669171998-05-06 19:52:49 +0000697\index{delimiters}
698
699\begin{verbatim}
Fred Drake6bd8e842004-08-05 21:11:27 +0000700( ) [ ] { } @
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000701, : . ` = ;
Fred Drakea7d608d2001-08-08 05:37:21 +0000702+= -= *= /= //= %=
703&= |= ^= >>= <<= **=
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000704\end{verbatim}
705
706The period can also occur in floating-point and imaginary literals. A
Fred Drakee15956b2000-04-03 04:51:13 +0000707sequence of three periods has a special meaning as an ellipsis in slices.
Thomas Wouters12bba852000-08-24 20:06:04 +0000708The second half of the list, the augmented assignment operators, serve
709lexically as delimiters, but also perform an operation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000710
Fred Drakec37b65e2001-11-28 07:26:15 +0000711The following printing \ASCII{} characters have special meaning as part
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000712of other tokens or are otherwise significant to the lexical analyzer:
713
714\begin{verbatim}
715' " # \
Fred Drakef6669171998-05-06 19:52:49 +0000716\end{verbatim}
717
718The following printing \ASCII{} characters are not used in Python. Their
719occurrence outside string literals and comments is an unconditional
720error:
Fred Drakec37b65e2001-11-28 07:26:15 +0000721\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000722
723\begin{verbatim}
Fred Drake6bd8e842004-08-05 21:11:27 +0000724$ ?
Fred Drakef6669171998-05-06 19:52:49 +0000725\end{verbatim}