blob: c8ecb4f6dbfad1db05ae070551e2aaa5cb8cef55 [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)
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000059character. On DOS/Windows, it is the \ASCII{} sequence CR LF (return
60followed 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
78the regular expression "coding[=:]\s*([\w-_.]+)", this comment is
79processed 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
94bytes of the file are the UTF-8 signature ($'\xef\xbb\xbf'$), the
95declared file encoding is UTF-8 (this is supported, among others, by
96Microsoft's notepad.exe).
97
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
104starts.
105
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 Drakec411fa61999-02-22 14:32:18 +0000152\subsection{Blank lines \index{blank line}\label{blank-lines}}
153
154A logical line that contains only spaces, tabs, formfeeds and possibly
155a comment, is ignored (i.e., no NEWLINE token is generated). During
156interactive input of statements, handling of a blank line may differ
157depending on the implementation of the read-eval-print loop. In the
158standard implementation, an entirely blank logical line (i.e.\ one
159containing not even whitespace or a comment) terminates a multi-line
160statement.
161
Fred Drakef6669171998-05-06 19:52:49 +0000162
Fred Drake61c77281998-07-28 19:34:22 +0000163\subsection{Indentation\label{indentation}}
Fred Drakef6669171998-05-06 19:52:49 +0000164
165Leading whitespace (spaces and tabs) at the beginning of a logical
166line is used to compute the indentation level of the line, which in
167turn is used to determine the grouping of statements.
168\index{indentation}
169\index{whitespace}
170\index{leading whitespace}
171\index{space}
172\index{tab}
173\index{grouping}
174\index{statement grouping}
175
176First, tabs are replaced (from left to right) by one to eight spaces
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000177such that the total number of characters up to and including the
178replacement is a multiple of
Fred Drakec37b65e2001-11-28 07:26:15 +0000179eight (this is intended to be the same rule as used by \UNIX). The
Fred Drakef6669171998-05-06 19:52:49 +0000180total number of spaces preceding the first non-blank character then
181determines the line's indentation. Indentation cannot be split over
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000182multiple physical lines using backslashes; the whitespace up to the
183first backslash determines the indentation.
184
185\strong{Cross-platform compatibility note:} because of the nature of
186text editors on non-UNIX platforms, it is unwise to use a mixture of
187spaces and tabs for the indentation in a single source file.
188
189A formfeed character may be present at the start of the line; it will
Fred Drakee15956b2000-04-03 04:51:13 +0000190be ignored for the indentation calculations above. Formfeed
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000191characters occurring elsewhere in the leading whitespace have an
192undefined effect (for instance, they may reset the space count to
193zero).
Fred Drakef6669171998-05-06 19:52:49 +0000194
195The indentation levels of consecutive lines are used to generate
196INDENT and DEDENT tokens, using a stack, as follows.
197\index{INDENT token}
198\index{DEDENT token}
199
200Before the first line of the file is read, a single zero is pushed on
201the stack; this will never be popped off again. The numbers pushed on
202the stack will always be strictly increasing from bottom to top. At
203the beginning of each logical line, the line's indentation level is
204compared to the top of the stack. If it is equal, nothing happens.
205If it is larger, it is pushed on the stack, and one INDENT token is
Fred Drake5c07d9b1998-05-14 19:37:06 +0000206generated. If it is smaller, it \emph{must} be one of the numbers
Fred Drakef6669171998-05-06 19:52:49 +0000207occurring on the stack; all numbers on the stack that are larger are
208popped off, and for each number popped off a DEDENT token is
209generated. At the end of the file, a DEDENT token is generated for
210each number remaining on the stack that is larger than zero.
211
212Here is an example of a correctly (though confusingly) indented piece
213of Python code:
214
215\begin{verbatim}
216def perm(l):
217 # Compute the list of all permutations of l
Fred Drakef6669171998-05-06 19:52:49 +0000218 if len(l) <= 1:
219 return [l]
220 r = []
221 for i in range(len(l)):
222 s = l[:i] + l[i+1:]
223 p = perm(s)
224 for x in p:
225 r.append(l[i:i+1] + x)
226 return r
227\end{verbatim}
228
229The following example shows various indentation errors:
230
231\begin{verbatim}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000232 def perm(l): # error: first line indented
233for i in range(len(l)): # error: not indented
234 s = l[:i] + l[i+1:]
235 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
236 for x in p:
237 r.append(l[i:i+1] + x)
238 return r # error: inconsistent dedent
Fred Drakef6669171998-05-06 19:52:49 +0000239\end{verbatim}
240
241(Actually, the first three errors are detected by the parser; only the
242last error is found by the lexical analyzer --- the indentation of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000243\code{return r} does not match a level popped off the stack.)
Fred Drakef6669171998-05-06 19:52:49 +0000244
Fred Drakef5eae662001-06-23 05:26:52 +0000245
Fred Drake61c77281998-07-28 19:34:22 +0000246\subsection{Whitespace between tokens\label{whitespace}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000247
248Except at the beginning of a logical line or in string literals, the
249whitespace characters space, tab and formfeed can be used
250interchangeably to separate tokens. Whitespace is needed between two
251tokens only if their concatenation could otherwise be interpreted as a
252different token (e.g., ab is one token, but a b is two tokens).
253
Fred Drakef5eae662001-06-23 05:26:52 +0000254
Fred Drake61c77281998-07-28 19:34:22 +0000255\section{Other tokens\label{other-tokens}}
Fred Drakef6669171998-05-06 19:52:49 +0000256
257Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000258exist: \emph{identifiers}, \emph{keywords}, \emph{literals},
259\emph{operators}, and \emph{delimiters}.
260Whitespace characters (other than line terminators, discussed earlier)
261are not tokens, but serve to delimit tokens.
262Where
Fred Drakef6669171998-05-06 19:52:49 +0000263ambiguity exists, a token comprises the longest possible string that
264forms a legal token, when read from left to right.
265
Fred Drakef5eae662001-06-23 05:26:52 +0000266
Fred Drake61c77281998-07-28 19:34:22 +0000267\section{Identifiers and keywords\label{identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +0000268
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000269Identifiers (also referred to as \emph{names}) are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000270lexical definitions:
271\index{identifier}
272\index{name}
273
Fred Drakecb4638a2001-07-06 22:49:53 +0000274\begin{productionlist}
275 \production{identifier}
276 {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
277 \production{letter}
278 {\token{lowercase} | \token{uppercase}}
279 \production{lowercase}
280 {"a"..."z"}
281 \production{uppercase}
282 {"A"..."Z"}
283 \production{digit}
284 {"0"..."9"}
285\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000286
287Identifiers are unlimited in length. Case is significant.
288
Fred Drakef5eae662001-06-23 05:26:52 +0000289
Fred Drake61c77281998-07-28 19:34:22 +0000290\subsection{Keywords\label{keywords}}
Fred Drakef6669171998-05-06 19:52:49 +0000291
Fred Drake5c07d9b1998-05-14 19:37:06 +0000292The following identifiers are used as reserved words, or
293\emph{keywords} of the language, and cannot be used as ordinary
294identifiers. They must be spelled exactly as written here:%
295\index{keyword}%
Fred Drakef6669171998-05-06 19:52:49 +0000296\index{reserved word}
297
298\begin{verbatim}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000299and del for is raise
300assert elif from lambda return
301break else global not try
Guido van Rossum41c67192001-12-04 20:38:44 +0000302class except if or while
303continue exec import pass yield
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000304def finally in print
Fred Drakef6669171998-05-06 19:52:49 +0000305\end{verbatim}
306
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000307% When adding keywords, use reswords.py for reformatting
308
Fred Drakea23b5732002-06-18 19:17:14 +0000309Note that although the identifier \code{as} can be used as part of the
310syntax of \keyword{import} statements, it is not currently a reserved
311word.
312
313In some future version of Python, the identifiers \code{as} and
314\code{None} will both become keywords.
315
Fred Drakef5eae662001-06-23 05:26:52 +0000316
Fred Drake61c77281998-07-28 19:34:22 +0000317\subsection{Reserved classes of identifiers\label{id-classes}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000318
319Certain classes of identifiers (besides keywords) have special
320meanings. These are:
321
Fred Drake39fc1bc1999-03-05 18:30:21 +0000322\begin{tableiii}{l|l|l}{code}{Form}{Meaning}{Notes}
323\lineiii{_*}{Not imported by \samp{from \var{module} import *}}{(1)}
324\lineiii{__*__}{System-defined name}{}
325\lineiii{__*}{Class-private name mangling}{}
326\end{tableiii}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000327
328(XXX need section references here.)
Fred Drakef6669171998-05-06 19:52:49 +0000329
Fred Drake39fc1bc1999-03-05 18:30:21 +0000330Note:
331
332\begin{description}
333\item[(1)] The special identifier \samp{_} is used in the interactive
334interpreter to store the result of the last evaluation; it is stored
335in the \module{__builtin__} module. When not in interactive mode,
336\samp{_} has no special meaning and is not defined.
337\end{description}
338
339
Fred Drake61c77281998-07-28 19:34:22 +0000340\section{Literals\label{literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000341
342Literals are notations for constant values of some built-in types.
343\index{literal}
344\index{constant}
345
Fred Drakef5eae662001-06-23 05:26:52 +0000346
Fred Drake61c77281998-07-28 19:34:22 +0000347\subsection{String literals\label{strings}}
Fred Drakef6669171998-05-06 19:52:49 +0000348
349String literals are described by the following lexical definitions:
350\index{string literal}
351
Fred Drakec37b65e2001-11-28 07:26:15 +0000352\index{ASCII@\ASCII}
Fred Drakecb4638a2001-07-06 22:49:53 +0000353\begin{productionlist}
354 \production{stringliteral}
Fred Drakec0cf7262001-08-14 21:43:31 +0000355 {[\token{stringprefix}](\token{shortstring} | \token{longstring})}
356 \production{stringprefix}
357 {"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000358 \production{shortstring}
359 {"'" \token{shortstringitem}* "'"
360 | '"' \token{shortstringitem}* '"'}
361 \production{longstring}
Fred Drake53815882002-03-15 23:21:37 +0000362 {"'''" \token{longstringitem}* "'''"}
363 \productioncont{| '"""' \token{longstringitem}* '"""'}
Fred Drakecb4638a2001-07-06 22:49:53 +0000364 \production{shortstringitem}
365 {\token{shortstringchar} | \token{escapeseq}}
366 \production{longstringitem}
367 {\token{longstringchar} | \token{escapeseq}}
368 \production{shortstringchar}
369 {<any ASCII character except "\e" or newline or the quote>}
370 \production{longstringchar}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000371 {<any ASCII character except "\e">}
Fred Drakecb4638a2001-07-06 22:49:53 +0000372 \production{escapeseq}
373 {"\e" <any ASCII character>}
374\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000375
Fred Drakec0cf7262001-08-14 21:43:31 +0000376One syntactic restriction not indicated by these productions is that
377whitespace is not allowed between the \grammartoken{stringprefix} and
378the rest of the string literal.
379
Fred Drakedea764d2000-12-19 04:52:03 +0000380\index{triple-quoted string}
381\index{Unicode Consortium}
382\index{string!Unicode}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000383In plain English: String literals can be enclosed in matching single
384quotes (\code{'}) or double quotes (\code{"}). They can also be
385enclosed in matching groups of three single or double quotes (these
386are generally referred to as \emph{triple-quoted strings}). The
387backslash (\code{\e}) character is used to escape characters that
388otherwise have a special meaning, such as newline, backslash itself,
389or the quote character. String literals may optionally be prefixed
Fred Drakec0cf7262001-08-14 21:43:31 +0000390with a letter `r' or `R'; such strings are called \dfn{raw
391strings}\index{raw string} and use different rules for interpreting
Fred Drakedea764d2000-12-19 04:52:03 +0000392backslash escape sequences. A prefix of 'u' or 'U' makes the string
393a Unicode string. Unicode strings use the Unicode character set as
394defined by the Unicode Consortium and ISO~10646. Some additional
395escape sequences, described below, are available in Unicode strings.
Fred Drakec0cf7262001-08-14 21:43:31 +0000396The two prefix characters may be combined; in this case, `u' must
397appear before `r'.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000398
399In triple-quoted strings,
Fred Drakef6669171998-05-06 19:52:49 +0000400unescaped newlines and quotes are allowed (and are retained), except
401that three unescaped quotes in a row terminate the string. (A
402``quote'' is the character used to open the string, i.e. either
Fred Drake5c07d9b1998-05-14 19:37:06 +0000403\code{'} or \code{"}.)
Fred Drakef6669171998-05-06 19:52:49 +0000404
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000405Unless an `r' or `R' prefix is present, escape sequences in strings
406are interpreted according to rules similar
Fred Drake90791642001-07-20 15:33:23 +0000407to those used by Standard C. The recognized escape sequences are:
Fred Drakef6669171998-05-06 19:52:49 +0000408\index{physical line}
409\index{escape sequence}
410\index{Standard C}
411\index{C}
412
Fred Drakea1cce711998-07-24 22:12:32 +0000413\begin{tableii}{l|l}{code}{Escape Sequence}{Meaning}
414\lineii{\e\var{newline}} {Ignored}
415\lineii{\e\e} {Backslash (\code{\e})}
416\lineii{\e'} {Single quote (\code{'})}
417\lineii{\e"} {Double quote (\code{"})}
418\lineii{\e a} {\ASCII{} Bell (BEL)}
419\lineii{\e b} {\ASCII{} Backspace (BS)}
420\lineii{\e f} {\ASCII{} Formfeed (FF)}
421\lineii{\e n} {\ASCII{} Linefeed (LF)}
Fred Drakedea764d2000-12-19 04:52:03 +0000422\lineii{\e N\{\var{name}\}}
423 {Character named \var{name} in the Unicode database (Unicode only)}
Fred Drakea1cce711998-07-24 22:12:32 +0000424\lineii{\e r} {\ASCII{} Carriage Return (CR)}
425\lineii{\e t} {\ASCII{} Horizontal Tab (TAB)}
Fred Drakec0cf7262001-08-14 21:43:31 +0000426\lineii{\e u\var{xxxx}} {Character with 16-bit hex value \var{xxxx} (Unicode only)}
427\lineii{\e U\var{xxxxxxxx}}{Character with 32-bit hex value \var{xxxxxxxx} (Unicode only)}
Fred Drakea1cce711998-07-24 22:12:32 +0000428\lineii{\e v} {\ASCII{} Vertical Tab (VT)}
Fred Drakedea764d2000-12-19 04:52:03 +0000429\lineii{\e\var{ooo}} {\ASCII{} character with octal value \var{ooo}}
430\lineii{\e x\var{hh}} {\ASCII{} character with hex value \var{hh}}
Fred Drakea1cce711998-07-24 22:12:32 +0000431\end{tableii}
Fred Drakec37b65e2001-11-28 07:26:15 +0000432\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000433
Tim Peters75302082001-02-14 04:03:51 +0000434As in Standard C, up to three octal digits are accepted. However,
435exactly two hex digits are taken in hex escapes.
Fred Drakef6669171998-05-06 19:52:49 +0000436
Fred Drakedea764d2000-12-19 04:52:03 +0000437Unlike Standard \index{unrecognized escape sequence}C,
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000438all unrecognized escape sequences are left in the string unchanged,
Fred Drakedea764d2000-12-19 04:52:03 +0000439i.e., \emph{the backslash is left in the string}. (This behavior is
Fred Drakef6669171998-05-06 19:52:49 +0000440useful when debugging: if an escape sequence is mistyped, the
Fred Drakedea764d2000-12-19 04:52:03 +0000441resulting output is more easily recognized as broken.) It is also
442important to note that the escape sequences marked as ``(Unicode
443only)'' in the table above fall into the category of unrecognized
444escapes for non-Unicode string literals.
Fred Drakef6669171998-05-06 19:52:49 +0000445
Fred Drake347a6252001-01-09 21:38:16 +0000446When an `r' or `R' prefix is present, a character following a
447backslash is included in the string without change, and \emph{all
448backslashes are left in the string}. For example, the string literal
449\code{r"\e n"} consists of two characters: a backslash and a lowercase
450`n'. String quotes can be escaped with a backslash, but the backslash
451remains in the string; for example, \code{r"\e""} is a valid string
452literal consisting of two characters: a backslash and a double quote;
Fred Drake0825dc22001-07-20 14:32:28 +0000453\code{r"\e"} is not a valid string literal (even a raw string cannot
Fred Drake347a6252001-01-09 21:38:16 +0000454end in an odd number of backslashes). Specifically, \emph{a raw
455string cannot end in a single backslash} (since the backslash would
456escape the following quote character). Note also that a single
457backslash followed by a newline is interpreted as those two characters
458as part of the string, \emph{not} as a line continuation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000459
Fred Drakef5eae662001-06-23 05:26:52 +0000460
Fred Drake61c77281998-07-28 19:34:22 +0000461\subsection{String literal concatenation\label{string-catenation}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000462
463Multiple adjacent string literals (delimited by whitespace), possibly
464using different quoting conventions, are allowed, and their meaning is
465the same as their concatenation. Thus, \code{"hello" 'world'} is
466equivalent to \code{"helloworld"}. This feature can be used to reduce
467the number of backslashes needed, to split long strings conveniently
468across long lines, or even to add comments to parts of strings, for
469example:
470
471\begin{verbatim}
472re.compile("[A-Za-z_]" # letter or underscore
473 "[A-Za-z0-9_]*" # letter, digit or underscore
474 )
475\end{verbatim}
476
477Note that this feature is defined at the syntactical level, but
478implemented at compile time. The `+' operator must be used to
479concatenate string expressions at run time. Also note that literal
480concatenation can use different quoting styles for each component
481(even mixing raw strings and triple quoted strings).
482
Fred Drake2ed27d32000-11-17 19:05:12 +0000483
Fred Drake61c77281998-07-28 19:34:22 +0000484\subsection{Numeric literals\label{numbers}}
Fred Drakef6669171998-05-06 19:52:49 +0000485
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000486There are four types of numeric literals: plain integers, long
487integers, floating point numbers, and imaginary numbers. There are no
488complex literals (complex numbers can be formed by adding a real
489number and an imaginary number).
Fred Drakef6669171998-05-06 19:52:49 +0000490\index{number}
491\index{numeric literal}
492\index{integer literal}
493\index{plain integer literal}
494\index{long integer literal}
495\index{floating point literal}
496\index{hexadecimal literal}
497\index{octal literal}
498\index{decimal literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000499\index{imaginary literal}
Fred Drakeed9e4532002-04-23 20:04:46 +0000500\index{complex!literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000501
502Note that numeric literals do not include a sign; a phrase like
503\code{-1} is actually an expression composed of the unary operator
504`\code{-}' and the literal \code{1}.
505
Fred Drakef5eae662001-06-23 05:26:52 +0000506
Fred Drake61c77281998-07-28 19:34:22 +0000507\subsection{Integer and long integer literals\label{integers}}
Fred Drakef6669171998-05-06 19:52:49 +0000508
509Integer and long integer literals are described by the following
510lexical definitions:
511
Fred Drakecb4638a2001-07-06 22:49:53 +0000512\begin{productionlist}
513 \production{longinteger}
514 {\token{integer} ("l" | "L")}
515 \production{integer}
516 {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
517 \production{decimalinteger}
518 {\token{nonzerodigit} \token{digit}* | "0"}
519 \production{octinteger}
520 {"0" \token{octdigit}+}
521 \production{hexinteger}
522 {"0" ("x" | "X") \token{hexdigit}+}
523 \production{nonzerodigit}
524 {"1"..."9"}
525 \production{octdigit}
526 {"0"..."7"}
527 \production{hexdigit}
528 {\token{digit} | "a"..."f" | "A"..."F"}
529\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000530
531Although both lower case `l' and upper case `L' are allowed as suffix
532for long integers, it is strongly recommended to always use `L', since
533the letter `l' looks too much like the digit `1'.
534
535Plain integer decimal literals must be at most 2147483647 (i.e., the
536largest positive integer, using 32-bit arithmetic). Plain octal and
537hexadecimal literals may be as large as 4294967295, but values larger
538than 2147483647 are converted to a negative value by subtracting
5394294967296. There is no limit for long integer literals apart from
540what can be stored in available memory.
541
542Some examples of plain and long integer literals:
543
544\begin{verbatim}
5457 2147483647 0177 0x80000000
5463L 79228162514264337593543950336L 0377L 0x100000000L
547\end{verbatim}
548
Fred Drakef5eae662001-06-23 05:26:52 +0000549
Fred Drake61c77281998-07-28 19:34:22 +0000550\subsection{Floating point literals\label{floating}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000551
Fred Drakef6669171998-05-06 19:52:49 +0000552Floating point literals are described by the following lexical
553definitions:
554
Fred Drakecb4638a2001-07-06 22:49:53 +0000555\begin{productionlist}
556 \production{floatnumber}
557 {\token{pointfloat} | \token{exponentfloat}}
558 \production{pointfloat}
559 {[\token{intpart}] \token{fraction} | \token{intpart} "."}
560 \production{exponentfloat}
Tim Petersd507dab2001-08-30 20:51:59 +0000561 {(\token{intpart} | \token{pointfloat})
Fred Drakecb4638a2001-07-06 22:49:53 +0000562 \token{exponent}}
563 \production{intpart}
Tim Petersd507dab2001-08-30 20:51:59 +0000564 {\token{digit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000565 \production{fraction}
566 {"." \token{digit}+}
567 \production{exponent}
568 {("e" | "E") ["+" | "-"] \token{digit}+}
569\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000570
Tim Petersd507dab2001-08-30 20:51:59 +0000571Note that the integer and exponent parts of floating point numbers
572can look like octal integers, but are interpreted using radix 10. For
573example, \samp{077e010} is legal, and denotes the same number
574as \samp{77e10}.
Fred Drakef6669171998-05-06 19:52:49 +0000575The allowed range of floating point literals is
576implementation-dependent.
Fred Drakef6669171998-05-06 19:52:49 +0000577Some examples of floating point literals:
578
579\begin{verbatim}
Tim Petersd507dab2001-08-30 20:51:59 +00005803.14 10. .001 1e100 3.14e-10 0e0
Fred Drakef6669171998-05-06 19:52:49 +0000581\end{verbatim}
582
583Note that numeric literals do not include a sign; a phrase like
Fred Drake5c07d9b1998-05-14 19:37:06 +0000584\code{-1} is actually an expression composed of the operator
585\code{-} and the literal \code{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000586
Fred Drakef5eae662001-06-23 05:26:52 +0000587
Fred Drake61c77281998-07-28 19:34:22 +0000588\subsection{Imaginary literals\label{imaginary}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000589
590Imaginary literals are described by the following lexical definitions:
591
Fred Drakecb4638a2001-07-06 22:49:53 +0000592\begin{productionlist}
593 \production{imagnumber}{(\token{floatnumber} | \token{intpart}) ("j" | "J")}
594\end{productionlist}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000595
Fred Drakee15956b2000-04-03 04:51:13 +0000596An imaginary literal yields a complex number with a real part of
Guido van Rossum60f2f0c1998-06-15 18:00:50 +00005970.0. Complex numbers are represented as a pair of floating point
598numbers and have the same restrictions on their range. To create a
599complex number with a nonzero real part, add a floating point number
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000600to it, e.g., \code{(3+4j)}. Some examples of imaginary literals:
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000601
602\begin{verbatim}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00006033.14j 10.j 10j .001j 1e100j 3.14e-10j
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000604\end{verbatim}
605
606
Fred Drake61c77281998-07-28 19:34:22 +0000607\section{Operators\label{operators}}
Fred Drakef6669171998-05-06 19:52:49 +0000608
609The following tokens are operators:
610\index{operators}
611
612\begin{verbatim}
Fred Drakea7d608d2001-08-08 05:37:21 +0000613+ - * ** / // %
Fred Drakef6669171998-05-06 19:52:49 +0000614<< >> & | ^ ~
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000615< > <= >= == != <>
Fred Drakef6669171998-05-06 19:52:49 +0000616\end{verbatim}
617
Fred Drake5c07d9b1998-05-14 19:37:06 +0000618The comparison operators \code{<>} and \code{!=} are alternate
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000619spellings of the same operator. \code{!=} is the preferred spelling;
620\code{<>} is obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000621
Fred Drakef5eae662001-06-23 05:26:52 +0000622
Fred Drake61c77281998-07-28 19:34:22 +0000623\section{Delimiters\label{delimiters}}
Fred Drakef6669171998-05-06 19:52:49 +0000624
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000625The following tokens serve as delimiters in the grammar:
Fred Drakef6669171998-05-06 19:52:49 +0000626\index{delimiters}
627
628\begin{verbatim}
629( ) [ ] { }
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000630, : . ` = ;
Fred Drakea7d608d2001-08-08 05:37:21 +0000631+= -= *= /= //= %=
632&= |= ^= >>= <<= **=
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000633\end{verbatim}
634
635The period can also occur in floating-point and imaginary literals. A
Fred Drakee15956b2000-04-03 04:51:13 +0000636sequence of three periods has a special meaning as an ellipsis in slices.
Thomas Wouters12bba852000-08-24 20:06:04 +0000637The second half of the list, the augmented assignment operators, serve
638lexically as delimiters, but also perform an operation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000639
Fred Drakec37b65e2001-11-28 07:26:15 +0000640The following printing \ASCII{} characters have special meaning as part
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000641of other tokens or are otherwise significant to the lexical analyzer:
642
643\begin{verbatim}
644' " # \
Fred Drakef6669171998-05-06 19:52:49 +0000645\end{verbatim}
646
647The following printing \ASCII{} characters are not used in Python. Their
648occurrence outside string literals and comments is an unconditional
649error:
Fred Drakec37b65e2001-11-28 07:26:15 +0000650\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000651
652\begin{verbatim}
653@ $ ?
654\end{verbatim}