blob: da7017afff0a3df54df7a7a188a6b30b7de03a22 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2.. _lexical:
3
4****************
5Lexical analysis
6****************
7
Georg Brandl57e3b682007-08-31 08:07:45 +00008.. index:: lexical analysis, parser, token
Georg Brandl116aa622007-08-15 14:28:22 +00009
10A Python program is read by a *parser*. Input to the parser is a stream of
11*tokens*, generated by the *lexical analyzer*. This chapter describes how the
12lexical analyzer breaks a file into tokens.
13
Georg Brandl57e3b682007-08-31 08:07:45 +000014Python reads program text as Unicode code points; the encoding of a source file
15can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120`
16for details. If the source file cannot be decoded, a :exc:`SyntaxError` is
17raised.
Georg Brandl116aa622007-08-15 14:28:22 +000018
19
20.. _line-structure:
21
22Line structure
23==============
24
Georg Brandl57e3b682007-08-31 08:07:45 +000025.. index:: line structure
Georg Brandl116aa622007-08-15 14:28:22 +000026
27A Python program is divided into a number of *logical lines*.
28
29
Georg Brandl57e3b682007-08-31 08:07:45 +000030.. _logical-lines:
Georg Brandl116aa622007-08-15 14:28:22 +000031
32Logical lines
33-------------
34
Georg Brandl57e3b682007-08-31 08:07:45 +000035.. index:: logical line, physical line, line joining, NEWLINE token
Georg Brandl116aa622007-08-15 14:28:22 +000036
37The end of a logical line is represented by the token NEWLINE. Statements
38cannot cross logical line boundaries except where NEWLINE is allowed by the
39syntax (e.g., between statements in compound statements). A logical line is
40constructed from one or more *physical lines* by following the explicit or
41implicit *line joining* rules.
42
43
Georg Brandl57e3b682007-08-31 08:07:45 +000044.. _physical-lines:
Georg Brandl116aa622007-08-15 14:28:22 +000045
46Physical lines
47--------------
48
49A physical line is a sequence of characters terminated by an end-of-line
50sequence. In source files, any of the standard platform line termination
51sequences can be used - the Unix form using ASCII LF (linefeed), the Windows
Georg Brandlc575c902008-09-13 17:46:05 +000052form using the ASCII sequence CR LF (return followed by linefeed), or the old
Georg Brandl116aa622007-08-15 14:28:22 +000053Macintosh form using the ASCII CR (return) character. All of these forms can be
54used equally, regardless of platform.
55
56When embedding Python, source code strings should be passed to Python APIs using
57the standard C conventions for newline characters (the ``\n`` character,
58representing ASCII LF, is the line terminator).
59
60
61.. _comments:
62
63Comments
64--------
65
Georg Brandl57e3b682007-08-31 08:07:45 +000066.. index:: comment, hash character
Georg Brandl116aa622007-08-15 14:28:22 +000067
68A comment starts with a hash character (``#``) that is not part of a string
69literal, and ends at the end of the physical line. A comment signifies the end
70of the logical line unless the implicit line joining rules are invoked. Comments
71are ignored by the syntax; they are not tokens.
72
73
74.. _encodings:
75
76Encoding declarations
77---------------------
78
R David Murrayf7f98182014-04-16 21:48:04 -040079.. index:: source character set, encoding declarations (source file)
Georg Brandl116aa622007-08-15 14:28:22 +000080
81If a comment in the first or second line of the Python script matches the
82regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
83encoding declaration; the first group of this expression names the encoding of
Robert Collins0b2833e2015-08-06 21:08:44 +120084the source code file. The encoding declaration must appear on a line of its
85own. If it is the second line, the first line must also be a comment-only line.
86The recommended forms of an encoding expression are ::
Georg Brandl116aa622007-08-15 14:28:22 +000087
88 # -*- coding: <encoding-name> -*-
89
90which is recognized also by GNU Emacs, and ::
91
92 # vim:fileencoding=<encoding-name>
93
Georg Brandl57e3b682007-08-31 08:07:45 +000094which is recognized by Bram Moolenaar's VIM.
95
96If no encoding declaration is found, the default encoding is UTF-8. In
97addition, if the first bytes of the file are the UTF-8 byte-order mark
98(``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported,
99among others, by Microsoft's :program:`notepad`).
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101If an encoding is declared, the encoding name must be recognized by Python. The
Georg Brandl57e3b682007-08-31 08:07:45 +0000102encoding is used for all lexical analysis, including string literals, comments
Robert Collins0b2833e2015-08-06 21:08:44 +1200103and identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000105.. XXX there should be a list of supported encodings.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107
108.. _explicit-joining:
109
110Explicit line joining
111---------------------
112
Georg Brandl57e3b682007-08-31 08:07:45 +0000113.. index:: physical line, line joining, line continuation, backslash character
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115Two or more physical lines may be joined into logical lines using backslash
116characters (``\``), as follows: when a physical line ends in a backslash that is
117not part of a string literal or comment, it is joined with the following forming
118a single logical line, deleting the backslash and the following end-of-line
Georg Brandl57e3b682007-08-31 08:07:45 +0000119character. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 if 1900 < year < 2100 and 1 <= month <= 12 \
122 and 1 <= day <= 31 and 0 <= hour < 24 \
123 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
124 return 1
125
126A line ending in a backslash cannot carry a comment. A backslash does not
127continue a comment. A backslash does not continue a token except for string
128literals (i.e., tokens other than string literals cannot be split across
129physical lines using a backslash). A backslash is illegal elsewhere on a line
130outside a string literal.
131
132
133.. _implicit-joining:
134
135Implicit line joining
136---------------------
137
138Expressions in parentheses, square brackets or curly braces can be split over
139more than one physical line without using backslashes. For example::
140
141 month_names = ['Januari', 'Februari', 'Maart', # These are the
142 'April', 'Mei', 'Juni', # Dutch names
143 'Juli', 'Augustus', 'September', # for the months
144 'Oktober', 'November', 'December'] # of the year
145
146Implicitly continued lines can carry comments. The indentation of the
147continuation lines is not important. Blank continuation lines are allowed.
148There is no NEWLINE token between implicit continuation lines. Implicitly
149continued lines can also occur within triple-quoted strings (see below); in that
150case they cannot carry comments.
151
152
153.. _blank-lines:
154
155Blank lines
156-----------
157
158.. index:: single: blank line
159
160A logical line that contains only spaces, tabs, formfeeds and possibly a
161comment, is ignored (i.e., no NEWLINE token is generated). During interactive
162input of statements, handling of a blank line may differ depending on the
Georg Brandl57e3b682007-08-31 08:07:45 +0000163implementation of the read-eval-print loop. In the standard interactive
164interpreter, an entirely blank logical line (i.e. one containing not even
165whitespace or a comment) terminates a multi-line statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167
168.. _indentation:
169
170Indentation
171-----------
172
Georg Brandl57e3b682007-08-31 08:07:45 +0000173.. index:: indentation, leading whitespace, space, tab, grouping, statement grouping
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175Leading whitespace (spaces and tabs) at the beginning of a logical line is used
176to compute the indentation level of the line, which in turn is used to determine
177the grouping of statements.
178
Georg Brandl861ac1f2008-12-15 08:43:10 +0000179Tabs are replaced (from left to right) by one to eight spaces such that the
180total number of characters up to and including the replacement is a multiple of
181eight (this is intended to be the same rule as used by Unix). The total number
182of spaces preceding the first non-blank character then determines the line's
183indentation. Indentation cannot be split over multiple physical lines using
184backslashes; the whitespace up to the first backslash determines the
Georg Brandl116aa622007-08-15 14:28:22 +0000185indentation.
186
Georg Brandl861ac1f2008-12-15 08:43:10 +0000187Indentation is rejected as inconsistent if a source file mixes tabs and spaces
188in a way that makes the meaning dependent on the worth of a tab in spaces; a
189:exc:`TabError` is raised in that case.
190
Georg Brandl116aa622007-08-15 14:28:22 +0000191**Cross-platform compatibility note:** because of the nature of text editors on
192non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
193indentation in a single source file. It should also be noted that different
194platforms may explicitly limit the maximum indentation level.
195
196A formfeed character may be present at the start of the line; it will be ignored
197for the indentation calculations above. Formfeed characters occurring elsewhere
198in the leading whitespace have an undefined effect (for instance, they may reset
199the space count to zero).
200
Georg Brandl57e3b682007-08-31 08:07:45 +0000201.. index:: INDENT token, DEDENT token
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203The indentation levels of consecutive lines are used to generate INDENT and
204DEDENT tokens, using a stack, as follows.
205
206Before the first line of the file is read, a single zero is pushed on the stack;
207this will never be popped off again. The numbers pushed on the stack will
208always be strictly increasing from bottom to top. At the beginning of each
209logical line, the line's indentation level is compared to the top of the stack.
210If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
211one INDENT token is generated. If it is smaller, it *must* be one of the
212numbers occurring on the stack; all numbers on the stack that are larger are
213popped off, and for each number popped off a DEDENT token is generated. At the
214end of the file, a DEDENT token is generated for each number remaining on the
215stack that is larger than zero.
216
217Here is an example of a correctly (though confusingly) indented piece of Python
218code::
219
220 def perm(l):
221 # Compute the list of all permutations of l
222 if len(l) <= 1:
223 return [l]
224 r = []
225 for i in range(len(l)):
226 s = l[:i] + l[i+1:]
227 p = perm(s)
228 for x in p:
229 r.append(l[i:i+1] + x)
230 return r
231
232The following example shows various indentation errors::
233
234 def perm(l): # error: first line indented
235 for i in range(len(l)): # error: not indented
236 s = l[:i] + l[i+1:]
237 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
238 for x in p:
239 r.append(l[i:i+1] + x)
240 return r # error: inconsistent dedent
241
242(Actually, the first three errors are detected by the parser; only the last
243error is found by the lexical analyzer --- the indentation of ``return r`` does
244not match a level popped off the stack.)
245
246
247.. _whitespace:
248
249Whitespace between tokens
250-------------------------
251
252Except at the beginning of a logical line or in string literals, the whitespace
253characters space, tab and formfeed can be used interchangeably to separate
254tokens. Whitespace is needed between two tokens only if their concatenation
255could otherwise be interpreted as a different token (e.g., ab is one token, but
256a b is two tokens).
257
258
259.. _other-tokens:
260
261Other tokens
262============
263
264Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
265*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
266characters (other than line terminators, discussed earlier) are not tokens, but
267serve to delimit tokens. Where ambiguity exists, a token comprises the longest
268possible string that forms a legal token, when read from left to right.
269
270
271.. _identifiers:
272
273Identifiers and keywords
274========================
275
Georg Brandl57e3b682007-08-31 08:07:45 +0000276.. index:: identifier, name
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278Identifiers (also referred to as *names*) are described by the following lexical
Georg Brandle06de8b2008-05-05 21:42:51 +0000279definitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl57e3b682007-08-31 08:07:45 +0000281The syntax of identifiers in Python is based on the Unicode standard annex
Georg Brandle06de8b2008-05-05 21:42:51 +0000282UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for
283further details.
Georg Brandl57e3b682007-08-31 08:07:45 +0000284
285Within the ASCII range (U+0001..U+007F), the valid characters for identifiers
Georg Brandle06de8b2008-05-05 21:42:51 +0000286are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through
287``Z``, the underscore ``_`` and, except for the first character, the digits
288``0`` through ``9``.
289
290Python 3.0 introduces additional characters from outside the ASCII range (see
291:pep:`3131`). For these characters, the classification uses the version of the
292Unicode Character Database as included in the :mod:`unicodedata` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294Identifiers are unlimited in length. Case is significant.
295
Georg Brandl57e3b682007-08-31 08:07:45 +0000296.. productionlist::
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000297 identifier: `xid_start` `xid_continue`*
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000298 id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
299 id_continue: <all characters in `id_start`, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000300 xid_start: <all characters in `id_start` whose NFKC normalization is in "id_start xid_continue*">
301 xid_continue: <all characters in `id_continue` whose NFKC normalization is in "id_continue*">
Georg Brandl57e3b682007-08-31 08:07:45 +0000302
303The Unicode category codes mentioned above stand for:
304
305* *Lu* - uppercase letters
306* *Ll* - lowercase letters
307* *Lt* - titlecase letters
308* *Lm* - modifier letters
309* *Lo* - other letters
310* *Nl* - letter numbers
311* *Mn* - nonspacing marks
312* *Mc* - spacing combining marks
313* *Nd* - decimal numbers
314* *Pc* - connector punctuations
R David Murray5f16f902014-10-09 20:45:59 -0400315* *Other_ID_Start* - explicit list of characters in `PropList.txt
Benjamin Peterson48013832015-06-27 15:45:56 -0500316 <http://www.unicode.org/Public/8.0.0/ucd/PropList.txt>`_ to support backwards
R David Murray5f16f902014-10-09 20:45:59 -0400317 compatibility
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000318* *Other_ID_Continue* - likewise
Georg Brandl57e3b682007-08-31 08:07:45 +0000319
Alexander Belopolsky1a7a2e02010-12-22 01:37:36 +0000320All identifiers are converted into the normal form NFKC while parsing; comparison
321of identifiers is based on NFKC.
Georg Brandl57e3b682007-08-31 08:07:45 +0000322
323A non-normative HTML file listing all valid identifier characters for Unicode
3244.1 can be found at
Serhiy Storchaka6dff0202016-05-07 10:49:07 +0300325https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html.
Georg Brandl116aa622007-08-15 14:28:22 +0000326
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000327
Georg Brandl116aa622007-08-15 14:28:22 +0000328.. _keywords:
329
330Keywords
331--------
332
333.. index::
334 single: keyword
335 single: reserved word
336
337The following identifiers are used as reserved words, or *keywords* of the
338language, and cannot be used as ordinary identifiers. They must be spelled
Georg Brandl17761d12009-05-04 20:43:44 +0000339exactly as written here:
340
341.. sourcecode:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000342
Georg Brandl57e3b682007-08-31 08:07:45 +0000343 False class finally is return
344 None continue for lambda try
345 True def from nonlocal while
346 and del global not with
347 as elif if or yield
348 assert else import pass
349 break except in raise
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351.. _id-classes:
352
353Reserved classes of identifiers
354-------------------------------
355
356Certain classes of identifiers (besides keywords) have special meanings. These
357classes are identified by the patterns of leading and trailing underscore
358characters:
359
360``_*``
361 Not imported by ``from module import *``. The special identifier ``_`` is used
362 in the interactive interpreter to store the result of the last evaluation; it is
Georg Brandl1a3284e2007-12-02 09:40:06 +0000363 stored in the :mod:`builtins` module. When not in interactive mode, ``_``
Georg Brandl116aa622007-08-15 14:28:22 +0000364 has no special meaning and is not defined. See section :ref:`import`.
365
366 .. note::
367
368 The name ``_`` is often used in conjunction with internationalization;
369 refer to the documentation for the :mod:`gettext` module for more
370 information on this convention.
371
372``__*__``
Georg Brandl7d180a02010-08-02 19:32:43 +0000373 System-defined names. These names are defined by the interpreter and its
374 implementation (including the standard library). Current system names are
375 discussed in the :ref:`specialnames` section and elsewhere. More will likely
376 be defined in future versions of Python. *Any* use of ``__*__`` names, in
377 any context, that does not follow explicitly documented use, is subject to
378 breakage without warning.
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380``__*``
381 Class-private names. Names in this category, when used within the context of a
382 class definition, are re-written to use a mangled form to help avoid name
383 clashes between "private" attributes of base and derived classes. See section
384 :ref:`atom-identifiers`.
385
386
387.. _literals:
388
389Literals
390========
391
Georg Brandl57e3b682007-08-31 08:07:45 +0000392.. index:: literal, constant
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394Literals are notations for constant values of some built-in types.
395
396
397.. _strings:
398
Georg Brandl57e3b682007-08-31 08:07:45 +0000399String and Bytes literals
400-------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000401
Georg Brandl57e3b682007-08-31 08:07:45 +0000402.. index:: string literal, bytes literal, ASCII
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404String literals are described by the following lexical definitions:
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406.. productionlist::
407 stringliteral: [`stringprefix`](`shortstring` | `longstring`)
Martin Panterbc1ee462016-02-13 00:41:37 +0000408 stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
409 : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
Georg Brandl116aa622007-08-15 14:28:22 +0000410 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
Georg Brandl57e3b682007-08-31 08:07:45 +0000411 longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
412 shortstringitem: `shortstringchar` | `stringescapeseq`
413 longstringitem: `longstringchar` | `stringescapeseq`
Georg Brandl116aa622007-08-15 14:28:22 +0000414 shortstringchar: <any source character except "\" or newline or the quote>
415 longstringchar: <any source character except "\">
Georg Brandl57e3b682007-08-31 08:07:45 +0000416 stringescapeseq: "\" <any source character>
417
418.. productionlist::
419 bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`)
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100420 bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
Georg Brandl57e3b682007-08-31 08:07:45 +0000421 shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"'
422 longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""'
423 shortbytesitem: `shortbyteschar` | `bytesescapeseq`
424 longbytesitem: `longbyteschar` | `bytesescapeseq`
425 shortbyteschar: <any ASCII character except "\" or newline or the quote>
426 longbyteschar: <any ASCII character except "\">
427 bytesescapeseq: "\" <any ASCII character>
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429One syntactic restriction not indicated by these productions is that whitespace
Georg Brandl57e3b682007-08-31 08:07:45 +0000430is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the
431rest of the literal. The source character set is defined by the encoding
432declaration; it is UTF-8 if no encoding declaration is given in the source file;
433see section :ref:`encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Georg Brandl57e3b682007-08-31 08:07:45 +0000435.. index:: triple-quoted string, Unicode Consortium, raw string
Georg Brandl116aa622007-08-15 14:28:22 +0000436
Georg Brandl57e3b682007-08-31 08:07:45 +0000437In plain English: Both types of literals can be enclosed in matching single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000438(``'``) or double quotes (``"``). They can also be enclosed in matching groups
439of three single or double quotes (these are generally referred to as
440*triple-quoted strings*). The backslash (``\``) character is used to escape
441characters that otherwise have a special meaning, such as newline, backslash
Georg Brandl57e3b682007-08-31 08:07:45 +0000442itself, or the quote character.
443
Georg Brandl57e3b682007-08-31 08:07:45 +0000444Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an
445instance of the :class:`bytes` type instead of the :class:`str` type. They
446may only contain ASCII characters; bytes with a numeric value of 128 or greater
447must be expressed with escapes.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Georg Brandla4c8c472014-10-31 10:38:49 +0100449As of Python 3.3 it is possible again to prefix string literals with a
Armin Ronacher50364b42012-03-04 12:33:51 +0000450``u`` prefix to simplify maintenance of dual 2.x and 3.x codebases.
451
Georg Brandl0182f382012-06-20 11:26:03 +0200452Both string and bytes literals may optionally be prefixed with a letter ``'r'``
Benjamin Peterson162dd742010-06-29 15:57:57 +0000453or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as
454literal characters. As a result, in string literals, ``'\U'`` and ``'\u'``
Christian Heimes0b3847d2012-06-20 11:17:58 +0200455escapes in raw strings are not treated specially. Given that Python 2.x's raw
456unicode literals behave differently than Python 3.x's the ``'ur'`` syntax
457is not supported.
Benjamin Peterson162dd742010-06-29 15:57:57 +0000458
Georg Brandla4c8c472014-10-31 10:38:49 +0100459.. versionadded:: 3.3
460 The ``'rb'`` prefix of raw bytes literals has been added as a synonym
461 of ``'br'``.
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100462
Georg Brandla4c8c472014-10-31 10:38:49 +0100463.. versionadded:: 3.3
464 Support for the unicode legacy literal (``u'value'``) was reintroduced
465 to simplify the maintenance of dual Python 2.x and 3.x codebases.
466 See :pep:`414` for more information.
Armin Ronacher50364b42012-03-04 12:33:51 +0000467
Martin Panterbc1ee462016-02-13 00:41:37 +0000468A string literal with ``'f'`` or ``'F'`` in its prefix is a
469:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be
470combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw
471formatted strings are possible, but formatted bytes literals are not.
472
Georg Brandla4c8c472014-10-31 10:38:49 +0100473In triple-quoted literals, unescaped newlines and quotes are allowed (and are
474retained), except that three unescaped quotes in a row terminate the literal. (A
475"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000476
Georg Brandl57e3b682007-08-31 08:07:45 +0000477.. index:: physical line, escape sequence, Standard C, C
Georg Brandl116aa622007-08-15 14:28:22 +0000478
Georg Brandla4c8c472014-10-31 10:38:49 +0100479Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and
480bytes literals are interpreted according to rules similar to those used by
481Standard C. The recognized escape sequences are:
Georg Brandl116aa622007-08-15 14:28:22 +0000482
483+-----------------+---------------------------------+-------+
484| Escape Sequence | Meaning | Notes |
485+=================+=================================+=======+
Georg Brandl57e3b682007-08-31 08:07:45 +0000486| ``\newline`` | Backslash and newline ignored | |
Georg Brandl116aa622007-08-15 14:28:22 +0000487+-----------------+---------------------------------+-------+
488| ``\\`` | Backslash (``\``) | |
489+-----------------+---------------------------------+-------+
490| ``\'`` | Single quote (``'``) | |
491+-----------------+---------------------------------+-------+
492| ``\"`` | Double quote (``"``) | |
493+-----------------+---------------------------------+-------+
494| ``\a`` | ASCII Bell (BEL) | |
495+-----------------+---------------------------------+-------+
496| ``\b`` | ASCII Backspace (BS) | |
497+-----------------+---------------------------------+-------+
498| ``\f`` | ASCII Formfeed (FF) | |
499+-----------------+---------------------------------+-------+
500| ``\n`` | ASCII Linefeed (LF) | |
501+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000502| ``\r`` | ASCII Carriage Return (CR) | |
503+-----------------+---------------------------------+-------+
504| ``\t`` | ASCII Horizontal Tab (TAB) | |
505+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000506| ``\v`` | ASCII Vertical Tab (VT) | |
507+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000508| ``\ooo`` | Character with octal value | (1,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000509| | *ooo* | |
510+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000511| ``\xhh`` | Character with hex value *hh* | (2,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000512+-----------------+---------------------------------+-------+
513
Georg Brandl57e3b682007-08-31 08:07:45 +0000514Escape sequences only recognized in string literals are:
515
516+-----------------+---------------------------------+-------+
517| Escape Sequence | Meaning | Notes |
518+=================+=================================+=======+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300519| ``\N{name}`` | Character named *name* in the | \(4) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000520| | Unicode database | |
521+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300522| ``\uxxxx`` | Character with 16-bit hex value | \(5) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000523| | *xxxx* | |
524+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300525| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(6) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000526| | *xxxxxxxx* | |
527+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529Notes:
530
531(1)
Georg Brandl57e3b682007-08-31 08:07:45 +0000532 As in Standard C, up to three octal digits are accepted.
533
534(2)
Florent Xicluna4e0f8912010-03-15 13:14:39 +0000535 Unlike in Standard C, exactly two hex digits are required.
Georg Brandl57e3b682007-08-31 08:07:45 +0000536
537(3)
538 In a bytes literal, hexadecimal and octal escapes denote the byte with the
539 given value. In a string literal, these escapes denote a Unicode character
540 with the given value.
541
542(4)
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300543 .. versionchanged:: 3.3
544 Support for name aliases [#]_ has been added.
545
546(5)
Berker Peksag4f35d792016-04-24 03:13:40 +0300547 Exactly four hex digits are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300549(6)
Ezio Melottie7f90372012-10-05 03:33:31 +0300550 Any Unicode character can be encoded this way. Exactly eight hex digits
Georg Brandle43baab2010-05-10 21:17:00 +0000551 are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000552
Georg Brandl116aa622007-08-15 14:28:22 +0000553
Georg Brandl57e3b682007-08-31 08:07:45 +0000554.. index:: unrecognized escape sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556Unlike Standard C, all unrecognized escape sequences are left in the string
Georg Brandla4c8c472014-10-31 10:38:49 +0100557unchanged, i.e., *the backslash is left in the result*. (This behavior is
Georg Brandl116aa622007-08-15 14:28:22 +0000558useful when debugging: if an escape sequence is mistyped, the resulting output
559is more easily recognized as broken.) It is also important to note that the
Georg Brandl57e3b682007-08-31 08:07:45 +0000560escape sequences only recognized in string literals fall into the category of
561unrecognized escapes for bytes literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000562
R David Murray110b6fe2016-09-08 15:34:08 -0400563 .. versionchanged:: 3.6
564 Unrecognized escape sequences produce a DeprecationWarning. In
565 some future version of Python they will be a SyntaxError.
566
Georg Brandla4c8c472014-10-31 10:38:49 +0100567Even in a raw literal, quotes can be escaped with a backslash, but the
568backslash remains in the result; for example, ``r"\""`` is a valid string
Georg Brandl57e3b682007-08-31 08:07:45 +0000569literal consisting of two characters: a backslash and a double quote; ``r"\"``
570is not a valid string literal (even a raw string cannot end in an odd number of
Georg Brandla4c8c472014-10-31 10:38:49 +0100571backslashes). Specifically, *a raw literal cannot end in a single backslash*
Georg Brandl57e3b682007-08-31 08:07:45 +0000572(since the backslash would escape the following quote character). Note also
573that a single backslash followed by a newline is interpreted as those two
Georg Brandla4c8c472014-10-31 10:38:49 +0100574characters as part of the literal, *not* as a line continuation.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
576
577.. _string-catenation:
578
579String literal concatenation
580----------------------------
581
Benjamin Peterson162dd742010-06-29 15:57:57 +0000582Multiple adjacent string or bytes literals (delimited by whitespace), possibly
583using different quoting conventions, are allowed, and their meaning is the same
584as their concatenation. Thus, ``"hello" 'world'`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +0000585``"helloworld"``. This feature can be used to reduce the number of backslashes
586needed, to split long strings conveniently across long lines, or even to add
587comments to parts of strings, for example::
588
589 re.compile("[A-Za-z_]" # letter or underscore
590 "[A-Za-z0-9_]*" # letter, digit or underscore
591 )
592
593Note that this feature is defined at the syntactical level, but implemented at
594compile time. The '+' operator must be used to concatenate string expressions
595at run time. Also note that literal concatenation can use different quoting
Martin Panterbc1ee462016-02-13 00:41:37 +0000596styles for each component (even mixing raw strings and triple quoted strings),
597and formatted string literals may be concatenated with plain string literals.
598
599
600.. index::
601 single: formatted string literal
602 single: interpolated string literal
603 single: string; formatted literal
604 single: string; interpolated literal
605 single: f-string
606.. _f-strings:
607
608Formatted string literals
609-------------------------
610
611.. versionadded:: 3.6
612
613A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
614that is prefixed with ``'f'`` or ``'F'``. These strings may contain
615replacement fields, which are expressions delimited by curly braces ``{}``.
616While other string literals always have a constant value, formatted strings
617are really expressions evaluated at run time.
618
619Escape sequences are decoded like in ordinary string literals (except when
620a literal is also marked as a raw string). After decoding, the grammar
621for the contents of the string is:
622
623.. productionlist::
624 f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
625 replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}"
Martin Pantered74e242016-06-12 01:56:24 +0000626 f_expression: (`conditional_expression` | "*" `or_expr`)
627 : ("," `conditional_expression` | "," "*" `or_expr`)* [","]
Martin Panterbc1ee462016-02-13 00:41:37 +0000628 : | `yield_expression`
629 conversion: "s" | "r" | "a"
630 format_spec: (`literal_char` | NULL | `replacement_field`)*
631 literal_char: <any code point except "{", "}" or NULL>
632
633The parts of the string outside curly braces are treated literally,
634except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
635with the corresponding single curly brace. A single opening curly
636bracket ``'{'`` marks a replacement field, which starts with a
637Python expression. After the expression, there may be a conversion field,
638introduced by an exclamation point ``'!'``. A format specifier may also
639be appended, introduced by a colon ``':'``. A replacement field ends
640with a closing curly bracket ``'}'``.
641
642Expressions in formatted string literals are treated like regular
643Python expressions surrounded by parentheses, with a few exceptions.
644An empty expression is not allowed, and a :keyword:`lambda` expression
645must be surrounded by explicit parentheses. Replacement expressions
646can contain line breaks (e.g. in triple-quoted strings), but they
647cannot contain comments. Each expression is evaluated in the context
648where the formatted string literal appears, in order from left to right.
649
650If a conversion is specified, the result of evaluating the expression
651is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
652the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
653
654The result is then formatted using the :func:`format` protocol. The
655format specifier is passed to the :meth:`__format__` method of the
656expression or conversion result. An empty string is passed when the
657format specifier is omitted. The formatted result is then included in
658the final value of the whole string.
659
660Top-level format specifiers may include nested replacement fields.
661These nested fields may include their own conversion fields and
662format specifiers, but may not include more deeply-nested replacement fields.
663
664Formatted string literals may be concatenated, but replacement fields
665cannot be split across literals.
666
667Some examples of formatted string literals::
668
669 >>> name = "Fred"
670 >>> f"He said his name is {name!r}."
671 "He said his name is 'Fred'."
672 >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
673 "He said his name is 'Fred'."
674 >>> width = 10
675 >>> precision = 4
676 >>> value = decimal.Decimal("12.34567")
677 >>> f"result: {value:{width}.{precision}}" # nested fields
678 'result: 12.35'
679
680A consequence of sharing the same syntax as regular string literals is
681that characters in the replacement fields must not conflict with the
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500682quoting used in the outer formatted string literal::
Martin Panterbc1ee462016-02-13 00:41:37 +0000683
684 f"abc {a["x"]} def" # error: outer string literal ended prematurely
Martin Panterbc1ee462016-02-13 00:41:37 +0000685 f"abc {a['x']} def" # workaround: use different quoting
686
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500687Backslashes are not allowed in format expressions and will raise
688an error::
689
690 f"newline: {ord('\n')}" # raises SyntaxError
691
692To include a value in which a backslash escape is required, create
693a temporary variable.
694
695 >>> newline = ord('\n')
696 >>> f"newline: {newline}"
697 'newline: 10'
Martin Panterbc1ee462016-02-13 00:41:37 +0000698
699See also :pep:`498` for the proposal that added formatted string literals,
700and :meth:`str.format`, which uses a related format string mechanism.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702
703.. _numbers:
704
705Numeric literals
706----------------
707
Georg Brandlba956ae2007-11-29 17:24:34 +0000708.. index:: number, numeric literal, integer literal
709 floating point literal, hexadecimal literal
Georg Brandl57e3b682007-08-31 08:07:45 +0000710 octal literal, binary literal, decimal literal, imaginary literal, complex literal
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Georg Brandl95817b32008-05-11 14:30:18 +0000712There are three types of numeric literals: integers, floating point numbers, and
713imaginary numbers. There are no complex literals (complex numbers can be formed
714by adding a real number and an imaginary number).
Georg Brandl116aa622007-08-15 14:28:22 +0000715
716Note that numeric literals do not include a sign; a phrase like ``-1`` is
717actually an expression composed of the unary operator '``-``' and the literal
718``1``.
719
720
721.. _integers:
722
723Integer literals
724----------------
725
726Integer literals are described by the following lexical definitions:
727
728.. productionlist::
Brett Cannona721aba2016-09-09 14:57:09 -0700729 integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger`
730 decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")*
731 bininteger: "0" ("b" | "B") (["_"] `bindigit`)+
732 octinteger: "0" ("o" | "O") (["_"] `octdigit`)+
733 hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+
Georg Brandl57e3b682007-08-31 08:07:45 +0000734 nonzerodigit: "1"..."9"
735 digit: "0"..."9"
Brett Cannona721aba2016-09-09 14:57:09 -0700736 bindigit: "0" | "1"
Georg Brandl116aa622007-08-15 14:28:22 +0000737 octdigit: "0"..."7"
738 hexdigit: `digit` | "a"..."f" | "A"..."F"
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Georg Brandl57e3b682007-08-31 08:07:45 +0000740There is no limit for the length of integer literals apart from what can be
741stored in available memory.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Brett Cannona721aba2016-09-09 14:57:09 -0700743Underscores are ignored for determining the numeric value of the literal. They
744can be used to group digits for enhanced readability. One underscore can occur
745between digits, and after base specifiers like ``0x``.
746
Georg Brandl116aa622007-08-15 14:28:22 +0000747Note that leading zeros in a non-zero decimal number are not allowed. This is
748for disambiguation with C-style octal literals, which Python used before version
7493.0.
750
751Some examples of integer literals::
752
753 7 2147483647 0o177 0b100110111
Raymond Hettinger9ecf9e22015-05-22 16:37:49 -0700754 3 79228162514264337593543950336 0o377 0xdeadbeef
Brett Cannona721aba2016-09-09 14:57:09 -0700755 100_000_000_000 0b_1110_0101
756
757.. versionchanged:: 3.6
758 Underscores are now allowed for grouping purposes in literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760
761.. _floating:
762
763Floating point literals
764-----------------------
765
766Floating point literals are described by the following lexical definitions:
767
768.. productionlist::
769 floatnumber: `pointfloat` | `exponentfloat`
Brett Cannona721aba2016-09-09 14:57:09 -0700770 pointfloat: [`digitpart`] `fraction` | `digitpart` "."
771 exponentfloat: (`digitpart` | `pointfloat`) `exponent`
772 digitpart: `digit` (["_"] `digit`)*
773 fraction: "." `digitpart`
774 exponent: ("e" | "E") ["+" | "-"] `digitpart`
Georg Brandl116aa622007-08-15 14:28:22 +0000775
776Note that the integer and exponent parts are always interpreted using radix 10.
777For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The
Brett Cannona721aba2016-09-09 14:57:09 -0700778allowed range of floating point literals is implementation-dependent. As in
779integer literals, underscores are supported for digit grouping.
Georg Brandl116aa622007-08-15 14:28:22 +0000780
Brett Cannona721aba2016-09-09 14:57:09 -0700781Some examples of floating point literals::
782
783 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785Note that numeric literals do not include a sign; a phrase like ``-1`` is
786actually an expression composed of the unary operator ``-`` and the literal
787``1``.
788
Brett Cannona721aba2016-09-09 14:57:09 -0700789.. versionchanged:: 3.6
790 Underscores are now allowed for grouping purposes in literals.
791
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793.. _imaginary:
794
795Imaginary literals
796------------------
797
798Imaginary literals are described by the following lexical definitions:
799
800.. productionlist::
Brett Cannona721aba2016-09-09 14:57:09 -0700801 imagnumber: (`floatnumber` | `digitpart`) ("j" | "J")
Georg Brandl116aa622007-08-15 14:28:22 +0000802
803An imaginary literal yields a complex number with a real part of 0.0. Complex
804numbers are represented as a pair of floating point numbers and have the same
805restrictions on their range. To create a complex number with a nonzero real
806part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
807imaginary literals::
808
Brett Cannona721aba2016-09-09 14:57:09 -0700809 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811
812.. _operators:
813
814Operators
815=========
816
817.. index:: single: operators
818
Martin Panter1050d2d2016-07-26 11:18:21 +0200819The following tokens are operators:
820
821.. code-block:: none
822
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Benjamin Petersonbd592412014-08-06 22:50:30 -0700824 + - * ** / // % @
Georg Brandl116aa622007-08-15 14:28:22 +0000825 << >> & | ^ ~
826 < > <= >= == !=
827
828
829.. _delimiters:
830
831Delimiters
832==========
833
834.. index:: single: delimiters
835
Martin Panter1050d2d2016-07-26 11:18:21 +0200836The following tokens serve as delimiters in the grammar:
837
838.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000839
Georg Brandl0df79792008-10-04 18:33:26 +0000840 ( ) [ ] { }
Georg Brandl97f96232013-10-08 21:28:22 +0200841 , : . ; @ = ->
Benjamin Petersonbd592412014-08-06 22:50:30 -0700842 += -= *= /= //= %= @=
Georg Brandl116aa622007-08-15 14:28:22 +0000843 &= |= ^= >>= <<= **=
844
845The period can also occur in floating-point and imaginary literals. A sequence
Georg Brandl57e3b682007-08-31 08:07:45 +0000846of three periods has a special meaning as an ellipsis literal. The second half
Georg Brandl116aa622007-08-15 14:28:22 +0000847of the list, the augmented assignment operators, serve lexically as delimiters,
848but also perform an operation.
849
850The following printing ASCII characters have special meaning as part of other
Martin Panter1050d2d2016-07-26 11:18:21 +0200851tokens or are otherwise significant to the lexical analyzer:
852
853.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855 ' " # \
856
Georg Brandl116aa622007-08-15 14:28:22 +0000857The following printing ASCII characters are not used in Python. Their
Martin Panter1050d2d2016-07-26 11:18:21 +0200858occurrence outside string literals and comments is an unconditional error:
859
860.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000861
Georg Brandle43baab2010-05-10 21:17:00 +0000862 $ ? `
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300863
864
865.. rubric:: Footnotes
866
Benjamin Peterson48013832015-06-27 15:45:56 -0500867.. [#] http://www.unicode.org/Public/8.0.0/ucd/NameAliases.txt