blob: 4ad8f8be1e7ddfb55ce3ff777a348f9d2bb600f5 [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
Ammar Askar0aa17ee2018-06-09 16:49:39 -070050sequence. In source files and strings, any of the standard platform line
51termination sequences can be used - the Unix form using ASCII LF (linefeed),
52the Windows form using the ASCII sequence CR LF (return followed by linefeed),
53or the old Macintosh form using the ASCII CR (return) character. All of these
54forms can be used equally, regardless of platform. The end of input also serves
55as an implicit terminator for the final physical line.
Georg Brandl116aa622007-08-15 14:28:22 +000056
57When embedding Python, source code strings should be passed to Python APIs using
58the standard C conventions for newline characters (the ``\n`` character,
59representing ASCII LF, is the line terminator).
60
61
62.. _comments:
63
64Comments
65--------
66
Georg Brandl57e3b682007-08-31 08:07:45 +000067.. index:: comment, hash character
Serhiy Storchaka913876d2018-10-28 13:41:26 +020068 single: # (hash); comment
Georg Brandl116aa622007-08-15 14:28:22 +000069
70A comment starts with a hash character (``#``) that is not part of a string
71literal, and ends at the end of the physical line. A comment signifies the end
72of the logical line unless the implicit line joining rules are invoked. Comments
divyag9778a9102019-05-13 08:05:20 -050073are ignored by the syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
76.. _encodings:
77
78Encoding declarations
79---------------------
80
R David Murrayf7f98182014-04-16 21:48:04 -040081.. index:: source character set, encoding declarations (source file)
Serhiy Storchaka913876d2018-10-28 13:41:26 +020082 single: # (hash); source encoding declaration
Georg Brandl116aa622007-08-15 14:28:22 +000083
84If a comment in the first or second line of the Python script matches the
85regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
86encoding declaration; the first group of this expression names the encoding of
Robert Collins0b2833e2015-08-06 21:08:44 +120087the source code file. The encoding declaration must appear on a line of its
88own. If it is the second line, the first line must also be a comment-only line.
89The recommended forms of an encoding expression are ::
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 # -*- coding: <encoding-name> -*-
92
93which is recognized also by GNU Emacs, and ::
94
95 # vim:fileencoding=<encoding-name>
96
Georg Brandl57e3b682007-08-31 08:07:45 +000097which is recognized by Bram Moolenaar's VIM.
98
99If no encoding declaration is found, the default encoding is UTF-8. In
100addition, if the first bytes of the file are the UTF-8 byte-order mark
101(``b'\xef\xbb\xbf'``), the declared file encoding is UTF-8 (this is supported,
102among others, by Microsoft's :program:`notepad`).
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104If an encoding is declared, the encoding name must be recognized by Python. The
Georg Brandl57e3b682007-08-31 08:07:45 +0000105encoding is used for all lexical analysis, including string literals, comments
Robert Collins0b2833e2015-08-06 21:08:44 +1200106and identifiers.
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000108.. XXX there should be a list of supported encodings.
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110
111.. _explicit-joining:
112
113Explicit line joining
114---------------------
115
Georg Brandl57e3b682007-08-31 08:07:45 +0000116.. index:: physical line, line joining, line continuation, backslash character
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118Two or more physical lines may be joined into logical lines using backslash
119characters (``\``), as follows: when a physical line ends in a backslash that is
120not part of a string literal or comment, it is joined with the following forming
121a single logical line, deleting the backslash and the following end-of-line
Georg Brandl57e3b682007-08-31 08:07:45 +0000122character. For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124 if 1900 < year < 2100 and 1 <= month <= 12 \
125 and 1 <= day <= 31 and 0 <= hour < 24 \
126 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
127 return 1
128
129A line ending in a backslash cannot carry a comment. A backslash does not
130continue a comment. A backslash does not continue a token except for string
131literals (i.e., tokens other than string literals cannot be split across
132physical lines using a backslash). A backslash is illegal elsewhere on a line
133outside a string literal.
134
135
136.. _implicit-joining:
137
138Implicit line joining
139---------------------
140
141Expressions in parentheses, square brackets or curly braces can be split over
142more than one physical line without using backslashes. For example::
143
144 month_names = ['Januari', 'Februari', 'Maart', # These are the
145 'April', 'Mei', 'Juni', # Dutch names
146 'Juli', 'Augustus', 'September', # for the months
147 'Oktober', 'November', 'December'] # of the year
148
149Implicitly continued lines can carry comments. The indentation of the
150continuation lines is not important. Blank continuation lines are allowed.
151There is no NEWLINE token between implicit continuation lines. Implicitly
152continued lines can also occur within triple-quoted strings (see below); in that
153case they cannot carry comments.
154
155
156.. _blank-lines:
157
158Blank lines
159-----------
160
161.. index:: single: blank line
162
163A logical line that contains only spaces, tabs, formfeeds and possibly a
164comment, is ignored (i.e., no NEWLINE token is generated). During interactive
165input of statements, handling of a blank line may differ depending on the
Georg Brandl57e3b682007-08-31 08:07:45 +0000166implementation of the read-eval-print loop. In the standard interactive
167interpreter, an entirely blank logical line (i.e. one containing not even
168whitespace or a comment) terminates a multi-line statement.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170
171.. _indentation:
172
173Indentation
174-----------
175
Georg Brandl57e3b682007-08-31 08:07:45 +0000176.. index:: indentation, leading whitespace, space, tab, grouping, statement grouping
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178Leading whitespace (spaces and tabs) at the beginning of a logical line is used
179to compute the indentation level of the line, which in turn is used to determine
180the grouping of statements.
181
Georg Brandl861ac1f2008-12-15 08:43:10 +0000182Tabs are replaced (from left to right) by one to eight spaces such that the
183total number of characters up to and including the replacement is a multiple of
184eight (this is intended to be the same rule as used by Unix). The total number
185of spaces preceding the first non-blank character then determines the line's
186indentation. Indentation cannot be split over multiple physical lines using
187backslashes; the whitespace up to the first backslash determines the
Georg Brandl116aa622007-08-15 14:28:22 +0000188indentation.
189
Georg Brandl861ac1f2008-12-15 08:43:10 +0000190Indentation is rejected as inconsistent if a source file mixes tabs and spaces
191in a way that makes the meaning dependent on the worth of a tab in spaces; a
192:exc:`TabError` is raised in that case.
193
Georg Brandl116aa622007-08-15 14:28:22 +0000194**Cross-platform compatibility note:** because of the nature of text editors on
195non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
196indentation in a single source file. It should also be noted that different
197platforms may explicitly limit the maximum indentation level.
198
199A formfeed character may be present at the start of the line; it will be ignored
200for the indentation calculations above. Formfeed characters occurring elsewhere
201in the leading whitespace have an undefined effect (for instance, they may reset
202the space count to zero).
203
Georg Brandl57e3b682007-08-31 08:07:45 +0000204.. index:: INDENT token, DEDENT token
Georg Brandl116aa622007-08-15 14:28:22 +0000205
206The indentation levels of consecutive lines are used to generate INDENT and
207DEDENT tokens, using a stack, as follows.
208
209Before the first line of the file is read, a single zero is pushed on the stack;
210this will never be popped off again. The numbers pushed on the stack will
211always be strictly increasing from bottom to top. At the beginning of each
212logical line, the line's indentation level is compared to the top of the stack.
213If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
214one INDENT token is generated. If it is smaller, it *must* be one of the
215numbers occurring on the stack; all numbers on the stack that are larger are
216popped off, and for each number popped off a DEDENT token is generated. At the
217end of the file, a DEDENT token is generated for each number remaining on the
218stack that is larger than zero.
219
220Here is an example of a correctly (though confusingly) indented piece of Python
221code::
222
223 def perm(l):
224 # Compute the list of all permutations of l
225 if len(l) <= 1:
226 return [l]
227 r = []
228 for i in range(len(l)):
229 s = l[:i] + l[i+1:]
230 p = perm(s)
231 for x in p:
232 r.append(l[i:i+1] + x)
233 return r
234
235The following example shows various indentation errors::
236
237 def perm(l): # error: first line indented
238 for i in range(len(l)): # error: not indented
239 s = l[:i] + l[i+1:]
240 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
241 for x in p:
242 r.append(l[i:i+1] + x)
243 return r # error: inconsistent dedent
244
245(Actually, the first three errors are detected by the parser; only the last
246error is found by the lexical analyzer --- the indentation of ``return r`` does
247not match a level popped off the stack.)
248
249
250.. _whitespace:
251
252Whitespace between tokens
253-------------------------
254
255Except at the beginning of a logical line or in string literals, the whitespace
256characters space, tab and formfeed can be used interchangeably to separate
257tokens. Whitespace is needed between two tokens only if their concatenation
258could otherwise be interpreted as a different token (e.g., ab is one token, but
259a b is two tokens).
260
261
262.. _other-tokens:
263
264Other tokens
265============
266
267Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
268*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
269characters (other than line terminators, discussed earlier) are not tokens, but
270serve to delimit tokens. Where ambiguity exists, a token comprises the longest
271possible string that forms a legal token, when read from left to right.
272
273
274.. _identifiers:
275
276Identifiers and keywords
277========================
278
Georg Brandl57e3b682007-08-31 08:07:45 +0000279.. index:: identifier, name
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281Identifiers (also referred to as *names*) are described by the following lexical
Georg Brandle06de8b2008-05-05 21:42:51 +0000282definitions.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl57e3b682007-08-31 08:07:45 +0000284The syntax of identifiers in Python is based on the Unicode standard annex
Georg Brandle06de8b2008-05-05 21:42:51 +0000285UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for
286further details.
Georg Brandl57e3b682007-08-31 08:07:45 +0000287
288Within the ASCII range (U+0001..U+007F), the valid characters for identifiers
Georg Brandle06de8b2008-05-05 21:42:51 +0000289are the same as in Python 2.x: the uppercase and lowercase letters ``A`` through
290``Z``, the underscore ``_`` and, except for the first character, the digits
291``0`` through ``9``.
292
293Python 3.0 introduces additional characters from outside the ASCII range (see
294:pep:`3131`). For these characters, the classification uses the version of the
295Unicode Character Database as included in the :mod:`unicodedata` module.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297Identifiers are unlimited in length. Case is significant.
298
Victor Stinner8af239e2020-09-18 09:10:15 +0200299.. productionlist:: python-grammar
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000300 identifier: `xid_start` `xid_continue`*
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000301 id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
302 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 +0000303 xid_start: <all characters in `id_start` whose NFKC normalization is in "id_start xid_continue*">
304 xid_continue: <all characters in `id_continue` whose NFKC normalization is in "id_continue*">
Georg Brandl57e3b682007-08-31 08:07:45 +0000305
306The Unicode category codes mentioned above stand for:
307
308* *Lu* - uppercase letters
309* *Ll* - lowercase letters
310* *Lt* - titlecase letters
311* *Lm* - modifier letters
312* *Lo* - other letters
313* *Nl* - letter numbers
314* *Mn* - nonspacing marks
315* *Mc* - spacing combining marks
316* *Nd* - decimal numbers
317* *Pc* - connector punctuations
R David Murray5f16f902014-10-09 20:45:59 -0400318* *Other_ID_Start* - explicit list of characters in `PropList.txt
Benjamin Peterson51796e52020-03-10 21:10:59 -0700319 <https://www.unicode.org/Public/13.0.0/ucd/PropList.txt>`_ to support backwards
R David Murray5f16f902014-10-09 20:45:59 -0400320 compatibility
Martin v. Löwis0dbebc02010-12-30 08:36:37 +0000321* *Other_ID_Continue* - likewise
Georg Brandl57e3b682007-08-31 08:07:45 +0000322
Alexander Belopolsky1a7a2e02010-12-22 01:37:36 +0000323All identifiers are converted into the normal form NFKC while parsing; comparison
324of identifiers is based on NFKC.
Georg Brandl57e3b682007-08-31 08:07:45 +0000325
326A non-normative HTML file listing all valid identifier characters for Unicode
3274.1 can be found at
Matteo Bertucciaf23f0d2020-05-23 03:12:09 +0200328https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt
Georg Brandl116aa622007-08-15 14:28:22 +0000329
Mark Summerfield051d1dd2007-11-20 13:22:19 +0000330
Georg Brandl116aa622007-08-15 14:28:22 +0000331.. _keywords:
332
333Keywords
334--------
335
336.. index::
337 single: keyword
338 single: reserved word
339
340The following identifiers are used as reserved words, or *keywords* of the
341language, and cannot be used as ordinary identifiers. They must be spelled
Georg Brandl17761d12009-05-04 20:43:44 +0000342exactly as written here:
343
344.. sourcecode:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000345
Tom Floyerbf9d3172017-11-08 20:31:26 +0300346 False await else import pass
347 None break except in raise
348 True class finally is return
349 and continue for lambda try
350 as def from nonlocal while
351 assert del global not with
352 async elif if or yield
Georg Brandl116aa622007-08-15 14:28:22 +0000353
Daniel F Moisseta22bca62021-03-01 04:08:38 +0000354
355.. _soft-keywords:
356
357Soft Keywords
358-------------
359
360.. index:: soft keyword, keyword
361
362.. versionadded:: 3.10
363
364Some identifiers are only reserved under specific contexts. These are known as
365*soft keywords*. The identifiers ``match``, ``case`` and ``_`` can
366syntactically act as keywords in contexts related to the pattern matching
367statement, but this distinction is done at the parser level, not when
368tokenizing.
369
370As soft keywords, their use with pattern matching is possible while still
371preserving compatibility with existing code that uses ``match``, ``case`` and ``_`` as
372identifier names.
373
374
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300375.. index::
376 single: _, identifiers
377 single: __, identifiers
Georg Brandl116aa622007-08-15 14:28:22 +0000378.. _id-classes:
379
380Reserved classes of identifiers
381-------------------------------
382
383Certain classes of identifiers (besides keywords) have special meanings. These
384classes are identified by the patterns of leading and trailing underscore
385characters:
386
387``_*``
388 Not imported by ``from module import *``. The special identifier ``_`` is used
389 in the interactive interpreter to store the result of the last evaluation; it is
Georg Brandl1a3284e2007-12-02 09:40:06 +0000390 stored in the :mod:`builtins` module. When not in interactive mode, ``_``
Georg Brandl116aa622007-08-15 14:28:22 +0000391 has no special meaning and is not defined. See section :ref:`import`.
392
393 .. note::
394
395 The name ``_`` is often used in conjunction with internationalization;
396 refer to the documentation for the :mod:`gettext` module for more
397 information on this convention.
398
399``__*__``
Javad Mokhtari5f9c1312020-03-27 23:32:51 +0430400 System-defined names, informally known as "dunder" names. These names are
401 defined by the interpreter and its implementation (including the standard library).
402 Current system names are discussed in the :ref:`specialnames` section and elsewhere.
403 More will likely be defined in future versions of Python. *Any* use of ``__*__`` names,
404 in any context, that does not follow explicitly documented use, is subject to
Georg Brandl7d180a02010-08-02 19:32:43 +0000405 breakage without warning.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407``__*``
408 Class-private names. Names in this category, when used within the context of a
409 class definition, are re-written to use a mangled form to help avoid name
410 clashes between "private" attributes of base and derived classes. See section
411 :ref:`atom-identifiers`.
412
413
414.. _literals:
415
416Literals
417========
418
Georg Brandl57e3b682007-08-31 08:07:45 +0000419.. index:: literal, constant
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421Literals are notations for constant values of some built-in types.
422
423
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300424.. index:: string literal, bytes literal, ASCII
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200425 single: ' (single quote); string literal
426 single: " (double quote); string literal
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300427 single: u'; string literal
428 single: u"; string literal
Georg Brandl116aa622007-08-15 14:28:22 +0000429.. _strings:
430
Georg Brandl57e3b682007-08-31 08:07:45 +0000431String and Bytes literals
432-------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Georg Brandl116aa622007-08-15 14:28:22 +0000434String literals are described by the following lexical definitions:
435
Victor Stinner8af239e2020-09-18 09:10:15 +0200436.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000437 stringliteral: [`stringprefix`](`shortstring` | `longstring`)
Martin Panterbc1ee462016-02-13 00:41:37 +0000438 stringprefix: "r" | "u" | "R" | "U" | "f" | "F"
439 : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
Georg Brandl116aa622007-08-15 14:28:22 +0000440 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
Georg Brandl57e3b682007-08-31 08:07:45 +0000441 longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""'
442 shortstringitem: `shortstringchar` | `stringescapeseq`
443 longstringitem: `longstringchar` | `stringescapeseq`
Georg Brandl116aa622007-08-15 14:28:22 +0000444 shortstringchar: <any source character except "\" or newline or the quote>
445 longstringchar: <any source character except "\">
Georg Brandl57e3b682007-08-31 08:07:45 +0000446 stringescapeseq: "\" <any source character>
447
Victor Stinner8af239e2020-09-18 09:10:15 +0200448.. productionlist:: python-grammar
Georg Brandl57e3b682007-08-31 08:07:45 +0000449 bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`)
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100450 bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
Georg Brandl57e3b682007-08-31 08:07:45 +0000451 shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"'
452 longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""'
453 shortbytesitem: `shortbyteschar` | `bytesescapeseq`
454 longbytesitem: `longbyteschar` | `bytesescapeseq`
455 shortbyteschar: <any ASCII character except "\" or newline or the quote>
456 longbyteschar: <any ASCII character except "\">
457 bytesescapeseq: "\" <any ASCII character>
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459One syntactic restriction not indicated by these productions is that whitespace
Georg Brandl57e3b682007-08-31 08:07:45 +0000460is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the
461rest of the literal. The source character set is defined by the encoding
462declaration; it is UTF-8 if no encoding declaration is given in the source file;
463see section :ref:`encodings`.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Georg Brandl57e3b682007-08-31 08:07:45 +0000465.. index:: triple-quoted string, Unicode Consortium, raw string
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300466 single: """; string literal
467 single: '''; string literal
Georg Brandl116aa622007-08-15 14:28:22 +0000468
Georg Brandl57e3b682007-08-31 08:07:45 +0000469In plain English: Both types of literals can be enclosed in matching single quotes
Georg Brandl116aa622007-08-15 14:28:22 +0000470(``'``) or double quotes (``"``). They can also be enclosed in matching groups
471of three single or double quotes (these are generally referred to as
472*triple-quoted strings*). The backslash (``\``) character is used to escape
473characters that otherwise have a special meaning, such as newline, backslash
Georg Brandl57e3b682007-08-31 08:07:45 +0000474itself, or the quote character.
475
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300476.. index::
477 single: b'; bytes literal
478 single: b"; bytes literal
479
Georg Brandl57e3b682007-08-31 08:07:45 +0000480Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an
481instance of the :class:`bytes` type instead of the :class:`str` type. They
482may only contain ASCII characters; bytes with a numeric value of 128 or greater
483must be expressed with escapes.
Georg Brandl116aa622007-08-15 14:28:22 +0000484
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300485.. index::
486 single: r'; raw string literal
487 single: r"; raw string literal
488
Georg Brandl0182f382012-06-20 11:26:03 +0200489Both string and bytes literals may optionally be prefixed with a letter ``'r'``
Benjamin Peterson162dd742010-06-29 15:57:57 +0000490or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as
491literal characters. As a result, in string literals, ``'\U'`` and ``'\u'``
Christian Heimes0b3847d2012-06-20 11:17:58 +0200492escapes in raw strings are not treated specially. Given that Python 2.x's raw
493unicode literals behave differently than Python 3.x's the ``'ur'`` syntax
494is not supported.
Benjamin Peterson162dd742010-06-29 15:57:57 +0000495
Georg Brandla4c8c472014-10-31 10:38:49 +0100496.. versionadded:: 3.3
497 The ``'rb'`` prefix of raw bytes literals has been added as a synonym
498 of ``'br'``.
Antoine Pitrou3a5d4cb2012-01-12 22:46:19 +0100499
Georg Brandla4c8c472014-10-31 10:38:49 +0100500.. versionadded:: 3.3
501 Support for the unicode legacy literal (``u'value'``) was reintroduced
502 to simplify the maintenance of dual Python 2.x and 3.x codebases.
503 See :pep:`414` for more information.
Armin Ronacher50364b42012-03-04 12:33:51 +0000504
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300505.. index::
506 single: f'; formatted string literal
507 single: f"; formatted string literal
508
Martin Panterbc1ee462016-02-13 00:41:37 +0000509A string literal with ``'f'`` or ``'F'`` in its prefix is a
510:dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be
511combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw
512formatted strings are possible, but formatted bytes literals are not.
513
Georg Brandla4c8c472014-10-31 10:38:49 +0100514In triple-quoted literals, unescaped newlines and quotes are allowed (and are
515retained), except that three unescaped quotes in a row terminate the literal. (A
516"quote" is the character used to open the literal, i.e. either ``'`` or ``"``.)
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Georg Brandl57e3b682007-08-31 08:07:45 +0000518.. index:: physical line, escape sequence, Standard C, C
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200519 single: \ (backslash); escape sequence
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300520 single: \\; escape sequence
521 single: \a; escape sequence
522 single: \b; escape sequence
523 single: \f; escape sequence
524 single: \n; escape sequence
525 single: \r; escape sequence
526 single: \t; escape sequence
527 single: \v; escape sequence
528 single: \x; escape sequence
529 single: \N; escape sequence
530 single: \u; escape sequence
531 single: \U; escape sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000532
Georg Brandla4c8c472014-10-31 10:38:49 +0100533Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and
534bytes literals are interpreted according to rules similar to those used by
535Standard C. The recognized escape sequences are:
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537+-----------------+---------------------------------+-------+
538| Escape Sequence | Meaning | Notes |
539+=================+=================================+=======+
Georg Brandl57e3b682007-08-31 08:07:45 +0000540| ``\newline`` | Backslash and newline ignored | |
Georg Brandl116aa622007-08-15 14:28:22 +0000541+-----------------+---------------------------------+-------+
542| ``\\`` | Backslash (``\``) | |
543+-----------------+---------------------------------+-------+
544| ``\'`` | Single quote (``'``) | |
545+-----------------+---------------------------------+-------+
546| ``\"`` | Double quote (``"``) | |
547+-----------------+---------------------------------+-------+
548| ``\a`` | ASCII Bell (BEL) | |
549+-----------------+---------------------------------+-------+
550| ``\b`` | ASCII Backspace (BS) | |
551+-----------------+---------------------------------+-------+
552| ``\f`` | ASCII Formfeed (FF) | |
553+-----------------+---------------------------------+-------+
554| ``\n`` | ASCII Linefeed (LF) | |
555+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000556| ``\r`` | ASCII Carriage Return (CR) | |
557+-----------------+---------------------------------+-------+
558| ``\t`` | ASCII Horizontal Tab (TAB) | |
559+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000560| ``\v`` | ASCII Vertical Tab (VT) | |
561+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000562| ``\ooo`` | Character with octal value | (1,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000563| | *ooo* | |
564+-----------------+---------------------------------+-------+
Georg Brandl57e3b682007-08-31 08:07:45 +0000565| ``\xhh`` | Character with hex value *hh* | (2,3) |
Georg Brandl116aa622007-08-15 14:28:22 +0000566+-----------------+---------------------------------+-------+
567
Georg Brandl57e3b682007-08-31 08:07:45 +0000568Escape sequences only recognized in string literals are:
569
570+-----------------+---------------------------------+-------+
571| Escape Sequence | Meaning | Notes |
572+=================+=================================+=======+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300573| ``\N{name}`` | Character named *name* in the | \(4) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000574| | Unicode database | |
575+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300576| ``\uxxxx`` | Character with 16-bit hex value | \(5) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000577| | *xxxx* | |
578+-----------------+---------------------------------+-------+
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300579| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(6) |
Georg Brandl57e3b682007-08-31 08:07:45 +0000580| | *xxxxxxxx* | |
581+-----------------+---------------------------------+-------+
Georg Brandl116aa622007-08-15 14:28:22 +0000582
583Notes:
584
585(1)
Georg Brandl57e3b682007-08-31 08:07:45 +0000586 As in Standard C, up to three octal digits are accepted.
587
588(2)
Florent Xicluna4e0f8912010-03-15 13:14:39 +0000589 Unlike in Standard C, exactly two hex digits are required.
Georg Brandl57e3b682007-08-31 08:07:45 +0000590
591(3)
592 In a bytes literal, hexadecimal and octal escapes denote the byte with the
593 given value. In a string literal, these escapes denote a Unicode character
594 with the given value.
595
596(4)
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300597 .. versionchanged:: 3.3
598 Support for name aliases [#]_ has been added.
599
600(5)
Berker Peksag4f35d792016-04-24 03:13:40 +0300601 Exactly four hex digits are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000602
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300603(6)
Ezio Melottie7f90372012-10-05 03:33:31 +0300604 Any Unicode character can be encoded this way. Exactly eight hex digits
Georg Brandle43baab2010-05-10 21:17:00 +0000605 are required.
Georg Brandl116aa622007-08-15 14:28:22 +0000606
Georg Brandl116aa622007-08-15 14:28:22 +0000607
Georg Brandl57e3b682007-08-31 08:07:45 +0000608.. index:: unrecognized escape sequence
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610Unlike Standard C, all unrecognized escape sequences are left in the string
Georg Brandla4c8c472014-10-31 10:38:49 +0100611unchanged, i.e., *the backslash is left in the result*. (This behavior is
Georg Brandl116aa622007-08-15 14:28:22 +0000612useful when debugging: if an escape sequence is mistyped, the resulting output
613is more easily recognized as broken.) It is also important to note that the
Georg Brandl57e3b682007-08-31 08:07:45 +0000614escape sequences only recognized in string literals fall into the category of
615unrecognized escapes for bytes literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000616
R David Murray110b6fe2016-09-08 15:34:08 -0400617 .. versionchanged:: 3.6
Gregory P. Smithb4be87a2019-08-10 00:19:07 -0700618 Unrecognized escape sequences produce a :exc:`DeprecationWarning`. In
619 a future Python version they will be a :exc:`SyntaxWarning` and
620 eventually a :exc:`SyntaxError`.
R David Murray110b6fe2016-09-08 15:34:08 -0400621
Georg Brandla4c8c472014-10-31 10:38:49 +0100622Even in a raw literal, quotes can be escaped with a backslash, but the
623backslash remains in the result; for example, ``r"\""`` is a valid string
Georg Brandl57e3b682007-08-31 08:07:45 +0000624literal consisting of two characters: a backslash and a double quote; ``r"\"``
625is not a valid string literal (even a raw string cannot end in an odd number of
Georg Brandla4c8c472014-10-31 10:38:49 +0100626backslashes). Specifically, *a raw literal cannot end in a single backslash*
Georg Brandl57e3b682007-08-31 08:07:45 +0000627(since the backslash would escape the following quote character). Note also
628that a single backslash followed by a newline is interpreted as those two
Georg Brandla4c8c472014-10-31 10:38:49 +0100629characters as part of the literal, *not* as a line continuation.
Georg Brandl116aa622007-08-15 14:28:22 +0000630
631
İsmail Arılık3764bb02018-01-12 09:18:54 +0300632.. _string-concatenation:
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634String literal concatenation
635----------------------------
636
Benjamin Peterson162dd742010-06-29 15:57:57 +0000637Multiple adjacent string or bytes literals (delimited by whitespace), possibly
638using different quoting conventions, are allowed, and their meaning is the same
639as their concatenation. Thus, ``"hello" 'world'`` is equivalent to
Georg Brandl116aa622007-08-15 14:28:22 +0000640``"helloworld"``. This feature can be used to reduce the number of backslashes
641needed, to split long strings conveniently across long lines, or even to add
642comments to parts of strings, for example::
643
644 re.compile("[A-Za-z_]" # letter or underscore
645 "[A-Za-z0-9_]*" # letter, digit or underscore
646 )
647
648Note that this feature is defined at the syntactical level, but implemented at
649compile time. The '+' operator must be used to concatenate string expressions
650at run time. Also note that literal concatenation can use different quoting
Martin Panterbc1ee462016-02-13 00:41:37 +0000651styles for each component (even mixing raw strings and triple quoted strings),
652and formatted string literals may be concatenated with plain string literals.
653
654
655.. index::
656 single: formatted string literal
657 single: interpolated string literal
658 single: string; formatted literal
659 single: string; interpolated literal
660 single: f-string
amaajemyfren13efaec2020-07-28 01:31:02 +0300661 single: fstring
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200662 single: {} (curly brackets); in formatted string literal
663 single: ! (exclamation); in formatted string literal
664 single: : (colon); in formatted string literal
amaajemyfren13efaec2020-07-28 01:31:02 +0300665 single: = (equals); for help in debugging using string literals
Martin Panterbc1ee462016-02-13 00:41:37 +0000666.. _f-strings:
667
668Formatted string literals
669-------------------------
670
671.. versionadded:: 3.6
672
673A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal
674that is prefixed with ``'f'`` or ``'F'``. These strings may contain
675replacement fields, which are expressions delimited by curly braces ``{}``.
676While other string literals always have a constant value, formatted strings
677are really expressions evaluated at run time.
678
679Escape sequences are decoded like in ordinary string literals (except when
680a literal is also marked as a raw string). After decoding, the grammar
681for the contents of the string is:
682
Victor Stinner8af239e2020-09-18 09:10:15 +0200683.. productionlist:: python-grammar
Martin Panterbc1ee462016-02-13 00:41:37 +0000684 f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)*
amaajemyfren13efaec2020-07-28 01:31:02 +0300685 replacement_field: "{" `f_expression` ["="] ["!" `conversion`] [":" `format_spec`] "}"
Martin Pantered74e242016-06-12 01:56:24 +0000686 f_expression: (`conditional_expression` | "*" `or_expr`)
687 : ("," `conditional_expression` | "," "*" `or_expr`)* [","]
Martin Panterbc1ee462016-02-13 00:41:37 +0000688 : | `yield_expression`
689 conversion: "s" | "r" | "a"
690 format_spec: (`literal_char` | NULL | `replacement_field`)*
691 literal_char: <any code point except "{", "}" or NULL>
692
693The parts of the string outside curly braces are treated literally,
694except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced
695with the corresponding single curly brace. A single opening curly
696bracket ``'{'`` marks a replacement field, which starts with a
amaajemyfren13efaec2020-07-28 01:31:02 +0300697Python expression. To display both the expression text and its value after
698evaluation, (useful in debugging), an equal sign ``'='`` may be added after the
699expression. A conversion field, introduced by an exclamation point ``'!'`` may
700follow. A format specifier may also be appended, introduced by a colon ``':'``.
701A replacement field ends with a closing curly bracket ``'}'``.
Martin Panterbc1ee462016-02-13 00:41:37 +0000702
703Expressions in formatted string literals are treated like regular
704Python expressions surrounded by parentheses, with a few exceptions.
Logan Jonesae2c32f2019-05-06 12:32:44 -0400705An empty expression is not allowed, and both :keyword:`lambda` and
706assignment expressions ``:=`` must be surrounded by explicit parentheses.
707Replacement expressions can contain line breaks (e.g. in triple-quoted
708strings), but they cannot contain comments. Each expression is evaluated
709in the context where the formatted string literal appears, in order from
710left to right.
Martin Panterbc1ee462016-02-13 00:41:37 +0000711
Serhiy Storchakaf6327362020-02-14 01:57:35 +0200712.. versionchanged:: 3.7
713 Prior to Python 3.7, an :keyword:`await` expression and comprehensions
714 containing an :keyword:`async for` clause were illegal in the expressions
715 in formatted string literals due to a problem with the implementation.
716
amaajemyfren13efaec2020-07-28 01:31:02 +0300717When the equal sign ``'='`` is provided, the output will have the expression
718text, the ``'='`` and the evaluated value. Spaces after the opening brace
719``'{'``, within the expression and after the ``'='`` are all retained in the
720output. By default, the ``'='`` causes the :func:`repr` of the expression to be
721provided, unless there is a format specified. When a format is specified it
722defaults to the :func:`str` of the expression unless a conversion ``'!r'`` is
723declared.
724
725.. versionadded:: 3.8
Andre Delfino788b79f2020-09-10 03:33:13 -0300726 The equal sign ``'='``.
amaajemyfren13efaec2020-07-28 01:31:02 +0300727
Martin Panterbc1ee462016-02-13 00:41:37 +0000728If a conversion is specified, the result of evaluating the expression
729is converted before formatting. Conversion ``'!s'`` calls :func:`str` on
730the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`.
731
732The result is then formatted using the :func:`format` protocol. The
733format specifier is passed to the :meth:`__format__` method of the
734expression or conversion result. An empty string is passed when the
735format specifier is omitted. The formatted result is then included in
736the final value of the whole string.
737
KatherineMichelf4e21a22017-12-19 15:03:09 -0600738Top-level format specifiers may include nested replacement fields. These nested
739fields may include their own conversion fields and :ref:`format specifiers
740<formatspec>`, but may not include more deeply-nested replacement fields. The
741:ref:`format specifier mini-language <formatspec>` is the same as that used by
Géry Ogame2fb8a22020-06-12 14:54:29 +0200742the :meth:`str.format` method.
Martin Panterbc1ee462016-02-13 00:41:37 +0000743
744Formatted string literals may be concatenated, but replacement fields
745cannot be split across literals.
746
747Some examples of formatted string literals::
748
749 >>> name = "Fred"
750 >>> f"He said his name is {name!r}."
751 "He said his name is 'Fred'."
752 >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
753 "He said his name is 'Fred'."
754 >>> width = 10
755 >>> precision = 4
756 >>> value = decimal.Decimal("12.34567")
757 >>> f"result: {value:{width}.{precision}}" # nested fields
758 'result: 12.35'
Mariattaf3618972017-09-16 11:46:43 -0700759 >>> today = datetime(year=2017, month=1, day=27)
Cheryl Sabellab2993932018-01-31 16:37:51 -0500760 >>> f"{today:%B %d, %Y}" # using date format specifier
Mariattaf3618972017-09-16 11:46:43 -0700761 'January 27, 2017'
amaajemyfren13efaec2020-07-28 01:31:02 +0300762 >>> f"{today=:%B %d, %Y}" # using date format specifier and debugging
763 'today=January 27, 2017'
Mariattaf3618972017-09-16 11:46:43 -0700764 >>> number = 1024
Mariatta63c591c2017-09-17 07:43:31 -0700765 >>> f"{number:#0x}" # using integer format specifier
Mariattaf3618972017-09-16 11:46:43 -0700766 '0x400'
amaajemyfren13efaec2020-07-28 01:31:02 +0300767 >>> foo = "bar"
768 >>> f"{ foo = }" # preserves whitespace
769 " foo = 'bar'"
770 >>> line = "The mill's closed"
771 >>> f"{line = }"
772 'line = "The mill\'s closed"'
773 >>> f"{line = :20}"
774 "line = The mill's closed "
775 >>> f"{line = !r:20}"
776 'line = "The mill\'s closed" '
777
Martin Panterbc1ee462016-02-13 00:41:37 +0000778
779A consequence of sharing the same syntax as regular string literals is
780that characters in the replacement fields must not conflict with the
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500781quoting used in the outer formatted string literal::
Martin Panterbc1ee462016-02-13 00:41:37 +0000782
783 f"abc {a["x"]} def" # error: outer string literal ended prematurely
Martin Panterbc1ee462016-02-13 00:41:37 +0000784 f"abc {a['x']} def" # workaround: use different quoting
785
Jason R. Coombsf66f03b2016-11-06 11:27:17 -0500786Backslashes are not allowed in format expressions and will raise
787an error::
788
789 f"newline: {ord('\n')}" # raises SyntaxError
790
791To include a value in which a backslash escape is required, create
792a temporary variable.
793
794 >>> newline = ord('\n')
795 >>> f"newline: {newline}"
796 'newline: 10'
Martin Panterbc1ee462016-02-13 00:41:37 +0000797
Mariattad4e89282017-03-10 08:58:40 -0800798Formatted string literals cannot be used as docstrings, even if they do not
799include expressions.
800
801::
802
803 >>> def foo():
804 ... f"Not a docstring"
805 ...
806 >>> foo.__doc__ is None
807 True
808
Martin Panterbc1ee462016-02-13 00:41:37 +0000809See also :pep:`498` for the proposal that added formatted string literals,
810and :meth:`str.format`, which uses a related format string mechanism.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
812
813.. _numbers:
814
815Numeric literals
816----------------
817
Georg Brandlba956ae2007-11-29 17:24:34 +0000818.. index:: number, numeric literal, integer literal
819 floating point literal, hexadecimal literal
Georg Brandl57e3b682007-08-31 08:07:45 +0000820 octal literal, binary literal, decimal literal, imaginary literal, complex literal
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Georg Brandl95817b32008-05-11 14:30:18 +0000822There are three types of numeric literals: integers, floating point numbers, and
823imaginary numbers. There are no complex literals (complex numbers can be formed
824by adding a real number and an imaginary number).
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826Note that numeric literals do not include a sign; a phrase like ``-1`` is
827actually an expression composed of the unary operator '``-``' and the literal
828``1``.
829
830
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300831.. index::
832 single: 0b; integer literal
833 single: 0o; integer literal
834 single: 0x; integer literal
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200835 single: _ (underscore); in numeric literal
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300836
Georg Brandl116aa622007-08-15 14:28:22 +0000837.. _integers:
838
839Integer literals
840----------------
841
842Integer literals are described by the following lexical definitions:
843
Victor Stinner8af239e2020-09-18 09:10:15 +0200844.. productionlist:: python-grammar
Brett Cannona721aba2016-09-09 14:57:09 -0700845 integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger`
846 decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")*
847 bininteger: "0" ("b" | "B") (["_"] `bindigit`)+
848 octinteger: "0" ("o" | "O") (["_"] `octdigit`)+
849 hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+
Georg Brandl57e3b682007-08-31 08:07:45 +0000850 nonzerodigit: "1"..."9"
851 digit: "0"..."9"
Brett Cannona721aba2016-09-09 14:57:09 -0700852 bindigit: "0" | "1"
Georg Brandl116aa622007-08-15 14:28:22 +0000853 octdigit: "0"..."7"
854 hexdigit: `digit` | "a"..."f" | "A"..."F"
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Georg Brandl57e3b682007-08-31 08:07:45 +0000856There is no limit for the length of integer literals apart from what can be
857stored in available memory.
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Brett Cannona721aba2016-09-09 14:57:09 -0700859Underscores are ignored for determining the numeric value of the literal. They
860can be used to group digits for enhanced readability. One underscore can occur
861between digits, and after base specifiers like ``0x``.
862
Georg Brandl116aa622007-08-15 14:28:22 +0000863Note that leading zeros in a non-zero decimal number are not allowed. This is
864for disambiguation with C-style octal literals, which Python used before version
8653.0.
866
867Some examples of integer literals::
868
869 7 2147483647 0o177 0b100110111
Raymond Hettinger9ecf9e22015-05-22 16:37:49 -0700870 3 79228162514264337593543950336 0o377 0xdeadbeef
Brett Cannona721aba2016-09-09 14:57:09 -0700871 100_000_000_000 0b_1110_0101
872
873.. versionchanged:: 3.6
874 Underscores are now allowed for grouping purposes in literals.
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300877.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200878 single: . (dot); in numeric literal
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300879 single: e; in numeric literal
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200880 single: _ (underscore); in numeric literal
Georg Brandl116aa622007-08-15 14:28:22 +0000881.. _floating:
882
883Floating point literals
884-----------------------
885
886Floating point literals are described by the following lexical definitions:
887
Victor Stinner8af239e2020-09-18 09:10:15 +0200888.. productionlist:: python-grammar
Georg Brandl116aa622007-08-15 14:28:22 +0000889 floatnumber: `pointfloat` | `exponentfloat`
Brett Cannona721aba2016-09-09 14:57:09 -0700890 pointfloat: [`digitpart`] `fraction` | `digitpart` "."
891 exponentfloat: (`digitpart` | `pointfloat`) `exponent`
892 digitpart: `digit` (["_"] `digit`)*
893 fraction: "." `digitpart`
894 exponent: ("e" | "E") ["+" | "-"] `digitpart`
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896Note that the integer and exponent parts are always interpreted using radix 10.
897For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The
Brett Cannona721aba2016-09-09 14:57:09 -0700898allowed range of floating point literals is implementation-dependent. As in
899integer literals, underscores are supported for digit grouping.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
Brett Cannona721aba2016-09-09 14:57:09 -0700901Some examples of floating point literals::
902
903 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Brett Cannona721aba2016-09-09 14:57:09 -0700905.. versionchanged:: 3.6
906 Underscores are now allowed for grouping purposes in literals.
907
Georg Brandl116aa622007-08-15 14:28:22 +0000908
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300909.. index::
910 single: j; in numeric literal
Georg Brandl116aa622007-08-15 14:28:22 +0000911.. _imaginary:
912
913Imaginary literals
914------------------
915
916Imaginary literals are described by the following lexical definitions:
917
Victor Stinner8af239e2020-09-18 09:10:15 +0200918.. productionlist:: python-grammar
Brett Cannona721aba2016-09-09 14:57:09 -0700919 imagnumber: (`floatnumber` | `digitpart`) ("j" | "J")
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921An imaginary literal yields a complex number with a real part of 0.0. Complex
922numbers are represented as a pair of floating point numbers and have the same
923restrictions on their range. To create a complex number with a nonzero real
924part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
925imaginary literals::
926
Brett Cannona721aba2016-09-09 14:57:09 -0700927 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j
Georg Brandl116aa622007-08-15 14:28:22 +0000928
929
930.. _operators:
931
932Operators
933=========
934
935.. index:: single: operators
936
Martin Panter1050d2d2016-07-26 11:18:21 +0200937The following tokens are operators:
938
939.. code-block:: none
940
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Benjamin Petersonbd592412014-08-06 22:50:30 -0700942 + - * ** / // % @
Emily Morehouse6357c952019-09-11 15:37:12 +0100943 << >> & | ^ ~ :=
Georg Brandl116aa622007-08-15 14:28:22 +0000944 < > <= >= == !=
945
946
947.. _delimiters:
948
949Delimiters
950==========
951
952.. index:: single: delimiters
953
Martin Panter1050d2d2016-07-26 11:18:21 +0200954The following tokens serve as delimiters in the grammar:
955
956.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000957
Georg Brandl0df79792008-10-04 18:33:26 +0000958 ( ) [ ] { }
Georg Brandl97f96232013-10-08 21:28:22 +0200959 , : . ; @ = ->
Benjamin Petersonbd592412014-08-06 22:50:30 -0700960 += -= *= /= //= %= @=
Georg Brandl116aa622007-08-15 14:28:22 +0000961 &= |= ^= >>= <<= **=
962
963The period can also occur in floating-point and imaginary literals. A sequence
Georg Brandl57e3b682007-08-31 08:07:45 +0000964of three periods has a special meaning as an ellipsis literal. The second half
Georg Brandl116aa622007-08-15 14:28:22 +0000965of the list, the augmented assignment operators, serve lexically as delimiters,
966but also perform an operation.
967
968The following printing ASCII characters have special meaning as part of other
Martin Panter1050d2d2016-07-26 11:18:21 +0200969tokens or are otherwise significant to the lexical analyzer:
970
971.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973 ' " # \
974
Georg Brandl116aa622007-08-15 14:28:22 +0000975The following printing ASCII characters are not used in Python. Their
Martin Panter1050d2d2016-07-26 11:18:21 +0200976occurrence outside string literals and comments is an unconditional error:
977
978.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000979
Georg Brandle43baab2010-05-10 21:17:00 +0000980 $ ? `
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300981
982
983.. rubric:: Footnotes
984
Benjamin Peterson51796e52020-03-10 21:10:59 -0700985.. [#] https://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt