Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 2 | .. _lexical: |
| 3 | |
| 4 | **************** |
| 5 | Lexical analysis |
| 6 | **************** |
| 7 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 8 | .. index:: lexical analysis, parser, token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
| 10 | A 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 |
| 12 | lexical analyzer breaks a file into tokens. |
| 13 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 14 | Python reads program text as Unicode code points; the encoding of a source file |
| 15 | can be given by an encoding declaration and defaults to UTF-8, see :pep:`3120` |
| 16 | for details. If the source file cannot be decoded, a :exc:`SyntaxError` is |
| 17 | raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | |
| 19 | |
| 20 | .. _line-structure: |
| 21 | |
| 22 | Line structure |
| 23 | ============== |
| 24 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 25 | .. index:: line structure |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | |
| 27 | A Python program is divided into a number of *logical lines*. |
| 28 | |
| 29 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 30 | .. _logical-lines: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 31 | |
| 32 | Logical lines |
| 33 | ------------- |
| 34 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 35 | .. index:: logical line, physical line, line joining, NEWLINE token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 | |
| 37 | The end of a logical line is represented by the token NEWLINE. Statements |
| 38 | cannot cross logical line boundaries except where NEWLINE is allowed by the |
| 39 | syntax (e.g., between statements in compound statements). A logical line is |
| 40 | constructed from one or more *physical lines* by following the explicit or |
| 41 | implicit *line joining* rules. |
| 42 | |
| 43 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 44 | .. _physical-lines: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 | |
| 46 | Physical lines |
| 47 | -------------- |
| 48 | |
| 49 | A physical line is a sequence of characters terminated by an end-of-line |
Ammar Askar | 0aa17ee | 2018-06-09 16:49:39 -0700 | [diff] [blame] | 50 | sequence. In source files and strings, any of the standard platform line |
| 51 | termination sequences can be used - the Unix form using ASCII LF (linefeed), |
| 52 | the Windows form using the ASCII sequence CR LF (return followed by linefeed), |
| 53 | or the old Macintosh form using the ASCII CR (return) character. All of these |
| 54 | forms can be used equally, regardless of platform. The end of input also serves |
| 55 | as an implicit terminator for the final physical line. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 56 | |
| 57 | When embedding Python, source code strings should be passed to Python APIs using |
| 58 | the standard C conventions for newline characters (the ``\n`` character, |
| 59 | representing ASCII LF, is the line terminator). |
| 60 | |
| 61 | |
| 62 | .. _comments: |
| 63 | |
| 64 | Comments |
| 65 | -------- |
| 66 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 67 | .. index:: comment, hash character |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 68 | single: # (hash); comment |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 69 | |
| 70 | A comment starts with a hash character (``#``) that is not part of a string |
| 71 | literal, and ends at the end of the physical line. A comment signifies the end |
| 72 | of the logical line unless the implicit line joining rules are invoked. Comments |
| 73 | are ignored by the syntax; they are not tokens. |
| 74 | |
| 75 | |
| 76 | .. _encodings: |
| 77 | |
| 78 | Encoding declarations |
| 79 | --------------------- |
| 80 | |
R David Murray | f7f9818 | 2014-04-16 21:48:04 -0400 | [diff] [blame] | 81 | .. index:: source character set, encoding declarations (source file) |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 82 | single: # (hash); source encoding declaration |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 83 | |
| 84 | If a comment in the first or second line of the Python script matches the |
| 85 | regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an |
| 86 | encoding declaration; the first group of this expression names the encoding of |
Robert Collins | 0b2833e | 2015-08-06 21:08:44 +1200 | [diff] [blame] | 87 | the source code file. The encoding declaration must appear on a line of its |
| 88 | own. If it is the second line, the first line must also be a comment-only line. |
| 89 | The recommended forms of an encoding expression are :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | # -*- coding: <encoding-name> -*- |
| 92 | |
| 93 | which is recognized also by GNU Emacs, and :: |
| 94 | |
| 95 | # vim:fileencoding=<encoding-name> |
| 96 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 97 | which is recognized by Bram Moolenaar's VIM. |
| 98 | |
| 99 | If no encoding declaration is found, the default encoding is UTF-8. In |
| 100 | addition, 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, |
| 102 | among others, by Microsoft's :program:`notepad`). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 103 | |
| 104 | If an encoding is declared, the encoding name must be recognized by Python. The |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 105 | encoding is used for all lexical analysis, including string literals, comments |
Robert Collins | 0b2833e | 2015-08-06 21:08:44 +1200 | [diff] [blame] | 106 | and identifiers. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 107 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 108 | .. XXX there should be a list of supported encodings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 109 | |
| 110 | |
| 111 | .. _explicit-joining: |
| 112 | |
| 113 | Explicit line joining |
| 114 | --------------------- |
| 115 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 116 | .. index:: physical line, line joining, line continuation, backslash character |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 117 | |
| 118 | Two or more physical lines may be joined into logical lines using backslash |
| 119 | characters (``\``), as follows: when a physical line ends in a backslash that is |
| 120 | not part of a string literal or comment, it is joined with the following forming |
| 121 | a single logical line, deleting the backslash and the following end-of-line |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 122 | character. For example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
| 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 | |
| 129 | A line ending in a backslash cannot carry a comment. A backslash does not |
| 130 | continue a comment. A backslash does not continue a token except for string |
| 131 | literals (i.e., tokens other than string literals cannot be split across |
| 132 | physical lines using a backslash). A backslash is illegal elsewhere on a line |
| 133 | outside a string literal. |
| 134 | |
| 135 | |
| 136 | .. _implicit-joining: |
| 137 | |
| 138 | Implicit line joining |
| 139 | --------------------- |
| 140 | |
| 141 | Expressions in parentheses, square brackets or curly braces can be split over |
| 142 | more 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 | |
| 149 | Implicitly continued lines can carry comments. The indentation of the |
| 150 | continuation lines is not important. Blank continuation lines are allowed. |
| 151 | There is no NEWLINE token between implicit continuation lines. Implicitly |
| 152 | continued lines can also occur within triple-quoted strings (see below); in that |
| 153 | case they cannot carry comments. |
| 154 | |
| 155 | |
| 156 | .. _blank-lines: |
| 157 | |
| 158 | Blank lines |
| 159 | ----------- |
| 160 | |
| 161 | .. index:: single: blank line |
| 162 | |
| 163 | A logical line that contains only spaces, tabs, formfeeds and possibly a |
| 164 | comment, is ignored (i.e., no NEWLINE token is generated). During interactive |
| 165 | input of statements, handling of a blank line may differ depending on the |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 166 | implementation of the read-eval-print loop. In the standard interactive |
| 167 | interpreter, an entirely blank logical line (i.e. one containing not even |
| 168 | whitespace or a comment) terminates a multi-line statement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 169 | |
| 170 | |
| 171 | .. _indentation: |
| 172 | |
| 173 | Indentation |
| 174 | ----------- |
| 175 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 176 | .. index:: indentation, leading whitespace, space, tab, grouping, statement grouping |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | |
| 178 | Leading whitespace (spaces and tabs) at the beginning of a logical line is used |
| 179 | to compute the indentation level of the line, which in turn is used to determine |
| 180 | the grouping of statements. |
| 181 | |
Georg Brandl | 861ac1f | 2008-12-15 08:43:10 +0000 | [diff] [blame] | 182 | Tabs are replaced (from left to right) by one to eight spaces such that the |
| 183 | total number of characters up to and including the replacement is a multiple of |
| 184 | eight (this is intended to be the same rule as used by Unix). The total number |
| 185 | of spaces preceding the first non-blank character then determines the line's |
| 186 | indentation. Indentation cannot be split over multiple physical lines using |
| 187 | backslashes; the whitespace up to the first backslash determines the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 188 | indentation. |
| 189 | |
Georg Brandl | 861ac1f | 2008-12-15 08:43:10 +0000 | [diff] [blame] | 190 | Indentation is rejected as inconsistent if a source file mixes tabs and spaces |
| 191 | in 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | **Cross-platform compatibility note:** because of the nature of text editors on |
| 195 | non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the |
| 196 | indentation in a single source file. It should also be noted that different |
| 197 | platforms may explicitly limit the maximum indentation level. |
| 198 | |
| 199 | A formfeed character may be present at the start of the line; it will be ignored |
| 200 | for the indentation calculations above. Formfeed characters occurring elsewhere |
| 201 | in the leading whitespace have an undefined effect (for instance, they may reset |
| 202 | the space count to zero). |
| 203 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 204 | .. index:: INDENT token, DEDENT token |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 205 | |
| 206 | The indentation levels of consecutive lines are used to generate INDENT and |
| 207 | DEDENT tokens, using a stack, as follows. |
| 208 | |
| 209 | Before the first line of the file is read, a single zero is pushed on the stack; |
| 210 | this will never be popped off again. The numbers pushed on the stack will |
| 211 | always be strictly increasing from bottom to top. At the beginning of each |
| 212 | logical line, the line's indentation level is compared to the top of the stack. |
| 213 | If it is equal, nothing happens. If it is larger, it is pushed on the stack, and |
| 214 | one INDENT token is generated. If it is smaller, it *must* be one of the |
| 215 | numbers occurring on the stack; all numbers on the stack that are larger are |
| 216 | popped off, and for each number popped off a DEDENT token is generated. At the |
| 217 | end of the file, a DEDENT token is generated for each number remaining on the |
| 218 | stack that is larger than zero. |
| 219 | |
| 220 | Here is an example of a correctly (though confusingly) indented piece of Python |
| 221 | code:: |
| 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 | |
| 235 | The 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 |
| 246 | error is found by the lexical analyzer --- the indentation of ``return r`` does |
| 247 | not match a level popped off the stack.) |
| 248 | |
| 249 | |
| 250 | .. _whitespace: |
| 251 | |
| 252 | Whitespace between tokens |
| 253 | ------------------------- |
| 254 | |
| 255 | Except at the beginning of a logical line or in string literals, the whitespace |
| 256 | characters space, tab and formfeed can be used interchangeably to separate |
| 257 | tokens. Whitespace is needed between two tokens only if their concatenation |
| 258 | could otherwise be interpreted as a different token (e.g., ab is one token, but |
| 259 | a b is two tokens). |
| 260 | |
| 261 | |
| 262 | .. _other-tokens: |
| 263 | |
| 264 | Other tokens |
| 265 | ============ |
| 266 | |
| 267 | Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: |
| 268 | *identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace |
| 269 | characters (other than line terminators, discussed earlier) are not tokens, but |
| 270 | serve to delimit tokens. Where ambiguity exists, a token comprises the longest |
| 271 | possible string that forms a legal token, when read from left to right. |
| 272 | |
| 273 | |
| 274 | .. _identifiers: |
| 275 | |
| 276 | Identifiers and keywords |
| 277 | ======================== |
| 278 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 279 | .. index:: identifier, name |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 280 | |
| 281 | Identifiers (also referred to as *names*) are described by the following lexical |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 282 | definitions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 283 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 284 | The syntax of identifiers in Python is based on the Unicode standard annex |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 285 | UAX-31, with elaboration and changes as defined below; see also :pep:`3131` for |
| 286 | further details. |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 287 | |
| 288 | Within the ASCII range (U+0001..U+007F), the valid characters for identifiers |
Georg Brandl | e06de8b | 2008-05-05 21:42:51 +0000 | [diff] [blame] | 289 | are 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 | |
| 293 | Python 3.0 introduces additional characters from outside the ASCII range (see |
| 294 | :pep:`3131`). For these characters, the classification uses the version of the |
| 295 | Unicode Character Database as included in the :mod:`unicodedata` module. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
| 297 | Identifiers are unlimited in length. Case is significant. |
| 298 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 299 | .. productionlist:: |
Martin v. Löwis | 0dbebc0 | 2010-12-30 08:36:37 +0000 | [diff] [blame] | 300 | identifier: `xid_start` `xid_continue`* |
Mark Summerfield | 051d1dd | 2007-11-20 13:22:19 +0000 | [diff] [blame] | 301 | 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öwis | 0dbebc0 | 2010-12-30 08:36:37 +0000 | [diff] [blame] | 303 | 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 Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 305 | |
| 306 | The 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 Murray | 5f16f90 | 2014-10-09 20:45:59 -0400 | [diff] [blame] | 318 | * *Other_ID_Start* - explicit list of characters in `PropList.txt |
Benjamin Peterson | 738c19f | 2019-03-09 16:25:55 -0800 | [diff] [blame^] | 319 | <http://www.unicode.org/Public/12.0.0/ucd/PropList.txt>`_ to support backwards |
R David Murray | 5f16f90 | 2014-10-09 20:45:59 -0400 | [diff] [blame] | 320 | compatibility |
Martin v. Löwis | 0dbebc0 | 2010-12-30 08:36:37 +0000 | [diff] [blame] | 321 | * *Other_ID_Continue* - likewise |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 322 | |
Alexander Belopolsky | 1a7a2e0 | 2010-12-22 01:37:36 +0000 | [diff] [blame] | 323 | All identifiers are converted into the normal form NFKC while parsing; comparison |
| 324 | of identifiers is based on NFKC. |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 325 | |
| 326 | A non-normative HTML file listing all valid identifier characters for Unicode |
| 327 | 4.1 can be found at |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 328 | https://www.dcl.hpi.uni-potsdam.de/home/loewis/table-3131.html. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 329 | |
Mark Summerfield | 051d1dd | 2007-11-20 13:22:19 +0000 | [diff] [blame] | 330 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 331 | .. _keywords: |
| 332 | |
| 333 | Keywords |
| 334 | -------- |
| 335 | |
| 336 | .. index:: |
| 337 | single: keyword |
| 338 | single: reserved word |
| 339 | |
| 340 | The following identifiers are used as reserved words, or *keywords* of the |
| 341 | language, and cannot be used as ordinary identifiers. They must be spelled |
Georg Brandl | 17761d1 | 2009-05-04 20:43:44 +0000 | [diff] [blame] | 342 | exactly as written here: |
| 343 | |
| 344 | .. sourcecode:: text |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 345 | |
Tom Floyer | bf9d317 | 2017-11-08 20:31:26 +0300 | [diff] [blame] | 346 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 353 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 354 | .. index:: |
| 355 | single: _, identifiers |
| 356 | single: __, identifiers |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 357 | .. _id-classes: |
| 358 | |
| 359 | Reserved classes of identifiers |
| 360 | ------------------------------- |
| 361 | |
| 362 | Certain classes of identifiers (besides keywords) have special meanings. These |
| 363 | classes are identified by the patterns of leading and trailing underscore |
| 364 | characters: |
| 365 | |
| 366 | ``_*`` |
| 367 | Not imported by ``from module import *``. The special identifier ``_`` is used |
| 368 | in the interactive interpreter to store the result of the last evaluation; it is |
Georg Brandl | 1a3284e | 2007-12-02 09:40:06 +0000 | [diff] [blame] | 369 | stored in the :mod:`builtins` module. When not in interactive mode, ``_`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 370 | has no special meaning and is not defined. See section :ref:`import`. |
| 371 | |
| 372 | .. note:: |
| 373 | |
| 374 | The name ``_`` is often used in conjunction with internationalization; |
| 375 | refer to the documentation for the :mod:`gettext` module for more |
| 376 | information on this convention. |
| 377 | |
| 378 | ``__*__`` |
Georg Brandl | 7d180a0 | 2010-08-02 19:32:43 +0000 | [diff] [blame] | 379 | System-defined names. These names are defined by the interpreter and its |
| 380 | implementation (including the standard library). Current system names are |
| 381 | discussed in the :ref:`specialnames` section and elsewhere. More will likely |
| 382 | be defined in future versions of Python. *Any* use of ``__*__`` names, in |
| 383 | any context, that does not follow explicitly documented use, is subject to |
| 384 | breakage without warning. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 385 | |
| 386 | ``__*`` |
| 387 | Class-private names. Names in this category, when used within the context of a |
| 388 | class definition, are re-written to use a mangled form to help avoid name |
| 389 | clashes between "private" attributes of base and derived classes. See section |
| 390 | :ref:`atom-identifiers`. |
| 391 | |
| 392 | |
| 393 | .. _literals: |
| 394 | |
| 395 | Literals |
| 396 | ======== |
| 397 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 398 | .. index:: literal, constant |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 399 | |
| 400 | Literals are notations for constant values of some built-in types. |
| 401 | |
| 402 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 403 | .. index:: string literal, bytes literal, ASCII |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 404 | single: ' (single quote); string literal |
| 405 | single: " (double quote); string literal |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 406 | single: u'; string literal |
| 407 | single: u"; string literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 408 | .. _strings: |
| 409 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 410 | String and Bytes literals |
| 411 | ------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 412 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 413 | String literals are described by the following lexical definitions: |
| 414 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 415 | .. productionlist:: |
| 416 | stringliteral: [`stringprefix`](`shortstring` | `longstring`) |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 417 | stringprefix: "r" | "u" | "R" | "U" | "f" | "F" |
| 418 | : | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 419 | shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"' |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 420 | longstring: "'''" `longstringitem`* "'''" | '"""' `longstringitem`* '"""' |
| 421 | shortstringitem: `shortstringchar` | `stringescapeseq` |
| 422 | longstringitem: `longstringchar` | `stringescapeseq` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | shortstringchar: <any source character except "\" or newline or the quote> |
| 424 | longstringchar: <any source character except "\"> |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 425 | stringescapeseq: "\" <any source character> |
| 426 | |
| 427 | .. productionlist:: |
| 428 | bytesliteral: `bytesprefix`(`shortbytes` | `longbytes`) |
Antoine Pitrou | 3a5d4cb | 2012-01-12 22:46:19 +0100 | [diff] [blame] | 429 | bytesprefix: "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB" |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 430 | shortbytes: "'" `shortbytesitem`* "'" | '"' `shortbytesitem`* '"' |
| 431 | longbytes: "'''" `longbytesitem`* "'''" | '"""' `longbytesitem`* '"""' |
| 432 | shortbytesitem: `shortbyteschar` | `bytesescapeseq` |
| 433 | longbytesitem: `longbyteschar` | `bytesescapeseq` |
| 434 | shortbyteschar: <any ASCII character except "\" or newline or the quote> |
| 435 | longbyteschar: <any ASCII character except "\"> |
| 436 | bytesescapeseq: "\" <any ASCII character> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 437 | |
| 438 | One syntactic restriction not indicated by these productions is that whitespace |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 439 | is not allowed between the :token:`stringprefix` or :token:`bytesprefix` and the |
| 440 | rest of the literal. The source character set is defined by the encoding |
| 441 | declaration; it is UTF-8 if no encoding declaration is given in the source file; |
| 442 | see section :ref:`encodings`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 443 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 444 | .. index:: triple-quoted string, Unicode Consortium, raw string |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 445 | single: """; string literal |
| 446 | single: '''; string literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 447 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 448 | In plain English: Both types of literals can be enclosed in matching single quotes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 449 | (``'``) or double quotes (``"``). They can also be enclosed in matching groups |
| 450 | of three single or double quotes (these are generally referred to as |
| 451 | *triple-quoted strings*). The backslash (``\``) character is used to escape |
| 452 | characters that otherwise have a special meaning, such as newline, backslash |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 453 | itself, or the quote character. |
| 454 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 455 | .. index:: |
| 456 | single: b'; bytes literal |
| 457 | single: b"; bytes literal |
| 458 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 459 | Bytes literals are always prefixed with ``'b'`` or ``'B'``; they produce an |
| 460 | instance of the :class:`bytes` type instead of the :class:`str` type. They |
| 461 | may only contain ASCII characters; bytes with a numeric value of 128 or greater |
| 462 | must be expressed with escapes. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 463 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 464 | .. index:: |
| 465 | single: r'; raw string literal |
| 466 | single: r"; raw string literal |
| 467 | |
Georg Brandl | 0182f38 | 2012-06-20 11:26:03 +0200 | [diff] [blame] | 468 | Both string and bytes literals may optionally be prefixed with a letter ``'r'`` |
Benjamin Peterson | 162dd74 | 2010-06-29 15:57:57 +0000 | [diff] [blame] | 469 | or ``'R'``; such strings are called :dfn:`raw strings` and treat backslashes as |
| 470 | literal characters. As a result, in string literals, ``'\U'`` and ``'\u'`` |
Christian Heimes | 0b3847d | 2012-06-20 11:17:58 +0200 | [diff] [blame] | 471 | escapes in raw strings are not treated specially. Given that Python 2.x's raw |
| 472 | unicode literals behave differently than Python 3.x's the ``'ur'`` syntax |
| 473 | is not supported. |
Benjamin Peterson | 162dd74 | 2010-06-29 15:57:57 +0000 | [diff] [blame] | 474 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 475 | .. versionadded:: 3.3 |
| 476 | The ``'rb'`` prefix of raw bytes literals has been added as a synonym |
| 477 | of ``'br'``. |
Antoine Pitrou | 3a5d4cb | 2012-01-12 22:46:19 +0100 | [diff] [blame] | 478 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 479 | .. versionadded:: 3.3 |
| 480 | Support for the unicode legacy literal (``u'value'``) was reintroduced |
| 481 | to simplify the maintenance of dual Python 2.x and 3.x codebases. |
| 482 | See :pep:`414` for more information. |
Armin Ronacher | 50364b4 | 2012-03-04 12:33:51 +0000 | [diff] [blame] | 483 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 484 | .. index:: |
| 485 | single: f'; formatted string literal |
| 486 | single: f"; formatted string literal |
| 487 | |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 488 | A string literal with ``'f'`` or ``'F'`` in its prefix is a |
| 489 | :dfn:`formatted string literal`; see :ref:`f-strings`. The ``'f'`` may be |
| 490 | combined with ``'r'``, but not with ``'b'`` or ``'u'``, therefore raw |
| 491 | formatted strings are possible, but formatted bytes literals are not. |
| 492 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 493 | In triple-quoted literals, unescaped newlines and quotes are allowed (and are |
| 494 | retained), except that three unescaped quotes in a row terminate the literal. (A |
| 495 | "quote" is the character used to open the literal, i.e. either ``'`` or ``"``.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 496 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 497 | .. index:: physical line, escape sequence, Standard C, C |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 498 | single: \ (backslash); escape sequence |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 499 | single: \\; escape sequence |
| 500 | single: \a; escape sequence |
| 501 | single: \b; escape sequence |
| 502 | single: \f; escape sequence |
| 503 | single: \n; escape sequence |
| 504 | single: \r; escape sequence |
| 505 | single: \t; escape sequence |
| 506 | single: \v; escape sequence |
| 507 | single: \x; escape sequence |
| 508 | single: \N; escape sequence |
| 509 | single: \u; escape sequence |
| 510 | single: \U; escape sequence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 511 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 512 | Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in string and |
| 513 | bytes literals are interpreted according to rules similar to those used by |
| 514 | Standard C. The recognized escape sequences are: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 515 | |
| 516 | +-----------------+---------------------------------+-------+ |
| 517 | | Escape Sequence | Meaning | Notes | |
| 518 | +=================+=================================+=======+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 519 | | ``\newline`` | Backslash and newline ignored | | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 520 | +-----------------+---------------------------------+-------+ |
| 521 | | ``\\`` | Backslash (``\``) | | |
| 522 | +-----------------+---------------------------------+-------+ |
| 523 | | ``\'`` | Single quote (``'``) | | |
| 524 | +-----------------+---------------------------------+-------+ |
| 525 | | ``\"`` | Double quote (``"``) | | |
| 526 | +-----------------+---------------------------------+-------+ |
| 527 | | ``\a`` | ASCII Bell (BEL) | | |
| 528 | +-----------------+---------------------------------+-------+ |
| 529 | | ``\b`` | ASCII Backspace (BS) | | |
| 530 | +-----------------+---------------------------------+-------+ |
| 531 | | ``\f`` | ASCII Formfeed (FF) | | |
| 532 | +-----------------+---------------------------------+-------+ |
| 533 | | ``\n`` | ASCII Linefeed (LF) | | |
| 534 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 535 | | ``\r`` | ASCII Carriage Return (CR) | | |
| 536 | +-----------------+---------------------------------+-------+ |
| 537 | | ``\t`` | ASCII Horizontal Tab (TAB) | | |
| 538 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 539 | | ``\v`` | ASCII Vertical Tab (VT) | | |
| 540 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 541 | | ``\ooo`` | Character with octal value | (1,3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 542 | | | *ooo* | | |
| 543 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 544 | | ``\xhh`` | Character with hex value *hh* | (2,3) | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 545 | +-----------------+---------------------------------+-------+ |
| 546 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 547 | Escape sequences only recognized in string literals are: |
| 548 | |
| 549 | +-----------------+---------------------------------+-------+ |
| 550 | | Escape Sequence | Meaning | Notes | |
| 551 | +=================+=================================+=======+ |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 552 | | ``\N{name}`` | Character named *name* in the | \(4) | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 553 | | | Unicode database | | |
| 554 | +-----------------+---------------------------------+-------+ |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 555 | | ``\uxxxx`` | Character with 16-bit hex value | \(5) | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 556 | | | *xxxx* | | |
| 557 | +-----------------+---------------------------------+-------+ |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 558 | | ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(6) | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 559 | | | *xxxxxxxx* | | |
| 560 | +-----------------+---------------------------------+-------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 561 | |
| 562 | Notes: |
| 563 | |
| 564 | (1) |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 565 | As in Standard C, up to three octal digits are accepted. |
| 566 | |
| 567 | (2) |
Florent Xicluna | 4e0f891 | 2010-03-15 13:14:39 +0000 | [diff] [blame] | 568 | Unlike in Standard C, exactly two hex digits are required. |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 569 | |
| 570 | (3) |
| 571 | In a bytes literal, hexadecimal and octal escapes denote the byte with the |
| 572 | given value. In a string literal, these escapes denote a Unicode character |
| 573 | with the given value. |
| 574 | |
| 575 | (4) |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 576 | .. versionchanged:: 3.3 |
| 577 | Support for name aliases [#]_ has been added. |
| 578 | |
| 579 | (5) |
Berker Peksag | 4f35d79 | 2016-04-24 03:13:40 +0300 | [diff] [blame] | 580 | Exactly four hex digits are required. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 581 | |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 582 | (6) |
Ezio Melotti | e7f9037 | 2012-10-05 03:33:31 +0300 | [diff] [blame] | 583 | Any Unicode character can be encoded this way. Exactly eight hex digits |
Georg Brandl | e43baab | 2010-05-10 21:17:00 +0000 | [diff] [blame] | 584 | are required. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 585 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 586 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 587 | .. index:: unrecognized escape sequence |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 588 | |
| 589 | Unlike Standard C, all unrecognized escape sequences are left in the string |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 590 | unchanged, i.e., *the backslash is left in the result*. (This behavior is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 591 | useful when debugging: if an escape sequence is mistyped, the resulting output |
| 592 | is more easily recognized as broken.) It is also important to note that the |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 593 | escape sequences only recognized in string literals fall into the category of |
| 594 | unrecognized escapes for bytes literals. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 595 | |
R David Murray | 110b6fe | 2016-09-08 15:34:08 -0400 | [diff] [blame] | 596 | .. versionchanged:: 3.6 |
Serhiy Storchaka | 6543912 | 2018-10-19 17:42:06 +0300 | [diff] [blame] | 597 | Unrecognized escape sequences produce a :exc:`DeprecationWarning`. |
| 598 | |
| 599 | .. versionchanged:: 3.8 |
| 600 | Unrecognized escape sequences produce a :exc:`SyntaxWarning`. In |
| 601 | some future version of Python they will be a :exc:`SyntaxError`. |
R David Murray | 110b6fe | 2016-09-08 15:34:08 -0400 | [diff] [blame] | 602 | |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 603 | Even in a raw literal, quotes can be escaped with a backslash, but the |
| 604 | backslash remains in the result; for example, ``r"\""`` is a valid string |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 605 | literal consisting of two characters: a backslash and a double quote; ``r"\"`` |
| 606 | is not a valid string literal (even a raw string cannot end in an odd number of |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 607 | backslashes). Specifically, *a raw literal cannot end in a single backslash* |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 608 | (since the backslash would escape the following quote character). Note also |
| 609 | that a single backslash followed by a newline is interpreted as those two |
Georg Brandl | a4c8c47 | 2014-10-31 10:38:49 +0100 | [diff] [blame] | 610 | characters as part of the literal, *not* as a line continuation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 611 | |
| 612 | |
İsmail Arılık | 3764bb0 | 2018-01-12 09:18:54 +0300 | [diff] [blame] | 613 | .. _string-concatenation: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 614 | |
| 615 | String literal concatenation |
| 616 | ---------------------------- |
| 617 | |
Benjamin Peterson | 162dd74 | 2010-06-29 15:57:57 +0000 | [diff] [blame] | 618 | Multiple adjacent string or bytes literals (delimited by whitespace), possibly |
| 619 | using different quoting conventions, are allowed, and their meaning is the same |
| 620 | as their concatenation. Thus, ``"hello" 'world'`` is equivalent to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 621 | ``"helloworld"``. This feature can be used to reduce the number of backslashes |
| 622 | needed, to split long strings conveniently across long lines, or even to add |
| 623 | comments to parts of strings, for example:: |
| 624 | |
| 625 | re.compile("[A-Za-z_]" # letter or underscore |
| 626 | "[A-Za-z0-9_]*" # letter, digit or underscore |
| 627 | ) |
| 628 | |
| 629 | Note that this feature is defined at the syntactical level, but implemented at |
| 630 | compile time. The '+' operator must be used to concatenate string expressions |
| 631 | at run time. Also note that literal concatenation can use different quoting |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 632 | styles for each component (even mixing raw strings and triple quoted strings), |
| 633 | and formatted string literals may be concatenated with plain string literals. |
| 634 | |
| 635 | |
| 636 | .. index:: |
| 637 | single: formatted string literal |
| 638 | single: interpolated string literal |
| 639 | single: string; formatted literal |
| 640 | single: string; interpolated literal |
| 641 | single: f-string |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 642 | single: {} (curly brackets); in formatted string literal |
| 643 | single: ! (exclamation); in formatted string literal |
| 644 | single: : (colon); in formatted string literal |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 645 | .. _f-strings: |
| 646 | |
| 647 | Formatted string literals |
| 648 | ------------------------- |
| 649 | |
| 650 | .. versionadded:: 3.6 |
| 651 | |
| 652 | A :dfn:`formatted string literal` or :dfn:`f-string` is a string literal |
| 653 | that is prefixed with ``'f'`` or ``'F'``. These strings may contain |
| 654 | replacement fields, which are expressions delimited by curly braces ``{}``. |
| 655 | While other string literals always have a constant value, formatted strings |
| 656 | are really expressions evaluated at run time. |
| 657 | |
| 658 | Escape sequences are decoded like in ordinary string literals (except when |
| 659 | a literal is also marked as a raw string). After decoding, the grammar |
| 660 | for the contents of the string is: |
| 661 | |
| 662 | .. productionlist:: |
| 663 | f_string: (`literal_char` | "{{" | "}}" | `replacement_field`)* |
| 664 | replacement_field: "{" `f_expression` ["!" `conversion`] [":" `format_spec`] "}" |
Martin Panter | ed74e24 | 2016-06-12 01:56:24 +0000 | [diff] [blame] | 665 | f_expression: (`conditional_expression` | "*" `or_expr`) |
| 666 | : ("," `conditional_expression` | "," "*" `or_expr`)* [","] |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 667 | : | `yield_expression` |
| 668 | conversion: "s" | "r" | "a" |
| 669 | format_spec: (`literal_char` | NULL | `replacement_field`)* |
| 670 | literal_char: <any code point except "{", "}" or NULL> |
| 671 | |
| 672 | The parts of the string outside curly braces are treated literally, |
| 673 | except that any doubled curly braces ``'{{'`` or ``'}}'`` are replaced |
| 674 | with the corresponding single curly brace. A single opening curly |
| 675 | bracket ``'{'`` marks a replacement field, which starts with a |
| 676 | Python expression. After the expression, there may be a conversion field, |
| 677 | introduced by an exclamation point ``'!'``. A format specifier may also |
| 678 | be appended, introduced by a colon ``':'``. A replacement field ends |
| 679 | with a closing curly bracket ``'}'``. |
| 680 | |
| 681 | Expressions in formatted string literals are treated like regular |
| 682 | Python expressions surrounded by parentheses, with a few exceptions. |
| 683 | An empty expression is not allowed, and a :keyword:`lambda` expression |
| 684 | must be surrounded by explicit parentheses. Replacement expressions |
| 685 | can contain line breaks (e.g. in triple-quoted strings), but they |
| 686 | cannot contain comments. Each expression is evaluated in the context |
| 687 | where the formatted string literal appears, in order from left to right. |
| 688 | |
| 689 | If a conversion is specified, the result of evaluating the expression |
| 690 | is converted before formatting. Conversion ``'!s'`` calls :func:`str` on |
| 691 | the result, ``'!r'`` calls :func:`repr`, and ``'!a'`` calls :func:`ascii`. |
| 692 | |
| 693 | The result is then formatted using the :func:`format` protocol. The |
| 694 | format specifier is passed to the :meth:`__format__` method of the |
| 695 | expression or conversion result. An empty string is passed when the |
| 696 | format specifier is omitted. The formatted result is then included in |
| 697 | the final value of the whole string. |
| 698 | |
KatherineMichel | f4e21a2 | 2017-12-19 15:03:09 -0600 | [diff] [blame] | 699 | Top-level format specifiers may include nested replacement fields. These nested |
| 700 | fields may include their own conversion fields and :ref:`format specifiers |
| 701 | <formatspec>`, but may not include more deeply-nested replacement fields. The |
| 702 | :ref:`format specifier mini-language <formatspec>` is the same as that used by |
| 703 | the string .format() method. |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 704 | |
| 705 | Formatted string literals may be concatenated, but replacement fields |
| 706 | cannot be split across literals. |
| 707 | |
| 708 | Some examples of formatted string literals:: |
| 709 | |
| 710 | >>> name = "Fred" |
| 711 | >>> f"He said his name is {name!r}." |
| 712 | "He said his name is 'Fred'." |
| 713 | >>> f"He said his name is {repr(name)}." # repr() is equivalent to !r |
| 714 | "He said his name is 'Fred'." |
| 715 | >>> width = 10 |
| 716 | >>> precision = 4 |
| 717 | >>> value = decimal.Decimal("12.34567") |
| 718 | >>> f"result: {value:{width}.{precision}}" # nested fields |
| 719 | 'result: 12.35' |
Mariatta | f361897 | 2017-09-16 11:46:43 -0700 | [diff] [blame] | 720 | >>> today = datetime(year=2017, month=1, day=27) |
Cheryl Sabella | b299393 | 2018-01-31 16:37:51 -0500 | [diff] [blame] | 721 | >>> f"{today:%B %d, %Y}" # using date format specifier |
Mariatta | f361897 | 2017-09-16 11:46:43 -0700 | [diff] [blame] | 722 | 'January 27, 2017' |
| 723 | >>> number = 1024 |
Mariatta | 63c591c | 2017-09-17 07:43:31 -0700 | [diff] [blame] | 724 | >>> f"{number:#0x}" # using integer format specifier |
Mariatta | f361897 | 2017-09-16 11:46:43 -0700 | [diff] [blame] | 725 | '0x400' |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 726 | |
| 727 | A consequence of sharing the same syntax as regular string literals is |
| 728 | that characters in the replacement fields must not conflict with the |
Jason R. Coombs | f66f03b | 2016-11-06 11:27:17 -0500 | [diff] [blame] | 729 | quoting used in the outer formatted string literal:: |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 730 | |
| 731 | f"abc {a["x"]} def" # error: outer string literal ended prematurely |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 732 | f"abc {a['x']} def" # workaround: use different quoting |
| 733 | |
Jason R. Coombs | f66f03b | 2016-11-06 11:27:17 -0500 | [diff] [blame] | 734 | Backslashes are not allowed in format expressions and will raise |
| 735 | an error:: |
| 736 | |
| 737 | f"newline: {ord('\n')}" # raises SyntaxError |
| 738 | |
| 739 | To include a value in which a backslash escape is required, create |
| 740 | a temporary variable. |
| 741 | |
| 742 | >>> newline = ord('\n') |
| 743 | >>> f"newline: {newline}" |
| 744 | 'newline: 10' |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 745 | |
Mariatta | d4e8928 | 2017-03-10 08:58:40 -0800 | [diff] [blame] | 746 | Formatted string literals cannot be used as docstrings, even if they do not |
| 747 | include expressions. |
| 748 | |
| 749 | :: |
| 750 | |
| 751 | >>> def foo(): |
| 752 | ... f"Not a docstring" |
| 753 | ... |
| 754 | >>> foo.__doc__ is None |
| 755 | True |
| 756 | |
Martin Panter | bc1ee46 | 2016-02-13 00:41:37 +0000 | [diff] [blame] | 757 | See also :pep:`498` for the proposal that added formatted string literals, |
| 758 | and :meth:`str.format`, which uses a related format string mechanism. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 759 | |
| 760 | |
| 761 | .. _numbers: |
| 762 | |
| 763 | Numeric literals |
| 764 | ---------------- |
| 765 | |
Georg Brandl | ba956ae | 2007-11-29 17:24:34 +0000 | [diff] [blame] | 766 | .. index:: number, numeric literal, integer literal |
| 767 | floating point literal, hexadecimal literal |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 768 | octal literal, binary literal, decimal literal, imaginary literal, complex literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 769 | |
Georg Brandl | 95817b3 | 2008-05-11 14:30:18 +0000 | [diff] [blame] | 770 | There are three types of numeric literals: integers, floating point numbers, and |
| 771 | imaginary numbers. There are no complex literals (complex numbers can be formed |
| 772 | by adding a real number and an imaginary number). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 773 | |
| 774 | Note that numeric literals do not include a sign; a phrase like ``-1`` is |
| 775 | actually an expression composed of the unary operator '``-``' and the literal |
| 776 | ``1``. |
| 777 | |
| 778 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 779 | .. index:: |
| 780 | single: 0b; integer literal |
| 781 | single: 0o; integer literal |
| 782 | single: 0x; integer literal |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 783 | single: _ (underscore); in numeric literal |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 784 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 785 | .. _integers: |
| 786 | |
| 787 | Integer literals |
| 788 | ---------------- |
| 789 | |
| 790 | Integer literals are described by the following lexical definitions: |
| 791 | |
| 792 | .. productionlist:: |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 793 | integer: `decinteger` | `bininteger` | `octinteger` | `hexinteger` |
| 794 | decinteger: `nonzerodigit` (["_"] `digit`)* | "0"+ (["_"] "0")* |
| 795 | bininteger: "0" ("b" | "B") (["_"] `bindigit`)+ |
| 796 | octinteger: "0" ("o" | "O") (["_"] `octdigit`)+ |
| 797 | hexinteger: "0" ("x" | "X") (["_"] `hexdigit`)+ |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 798 | nonzerodigit: "1"..."9" |
| 799 | digit: "0"..."9" |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 800 | bindigit: "0" | "1" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 801 | octdigit: "0"..."7" |
| 802 | hexdigit: `digit` | "a"..."f" | "A"..."F" |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 803 | |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 804 | There is no limit for the length of integer literals apart from what can be |
| 805 | stored in available memory. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 806 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 807 | Underscores are ignored for determining the numeric value of the literal. They |
| 808 | can be used to group digits for enhanced readability. One underscore can occur |
| 809 | between digits, and after base specifiers like ``0x``. |
| 810 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 811 | Note that leading zeros in a non-zero decimal number are not allowed. This is |
| 812 | for disambiguation with C-style octal literals, which Python used before version |
| 813 | 3.0. |
| 814 | |
| 815 | Some examples of integer literals:: |
| 816 | |
| 817 | 7 2147483647 0o177 0b100110111 |
Raymond Hettinger | 9ecf9e2 | 2015-05-22 16:37:49 -0700 | [diff] [blame] | 818 | 3 79228162514264337593543950336 0o377 0xdeadbeef |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 819 | 100_000_000_000 0b_1110_0101 |
| 820 | |
| 821 | .. versionchanged:: 3.6 |
| 822 | Underscores are now allowed for grouping purposes in literals. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 823 | |
| 824 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 825 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 826 | single: . (dot); in numeric literal |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 827 | single: e; in numeric literal |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 828 | single: _ (underscore); in numeric literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 829 | .. _floating: |
| 830 | |
| 831 | Floating point literals |
| 832 | ----------------------- |
| 833 | |
| 834 | Floating point literals are described by the following lexical definitions: |
| 835 | |
| 836 | .. productionlist:: |
| 837 | floatnumber: `pointfloat` | `exponentfloat` |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 838 | pointfloat: [`digitpart`] `fraction` | `digitpart` "." |
| 839 | exponentfloat: (`digitpart` | `pointfloat`) `exponent` |
| 840 | digitpart: `digit` (["_"] `digit`)* |
| 841 | fraction: "." `digitpart` |
| 842 | exponent: ("e" | "E") ["+" | "-"] `digitpart` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 843 | |
| 844 | Note that the integer and exponent parts are always interpreted using radix 10. |
| 845 | For example, ``077e010`` is legal, and denotes the same number as ``77e10``. The |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 846 | allowed range of floating point literals is implementation-dependent. As in |
| 847 | integer literals, underscores are supported for digit grouping. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 848 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 849 | Some examples of floating point literals:: |
| 850 | |
| 851 | 3.14 10. .001 1e100 3.14e-10 0e0 3.14_15_93 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 852 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 853 | .. versionchanged:: 3.6 |
| 854 | Underscores are now allowed for grouping purposes in literals. |
| 855 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 856 | |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 857 | .. index:: |
| 858 | single: j; in numeric literal |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 859 | .. _imaginary: |
| 860 | |
| 861 | Imaginary literals |
| 862 | ------------------ |
| 863 | |
| 864 | Imaginary literals are described by the following lexical definitions: |
| 865 | |
| 866 | .. productionlist:: |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 867 | imagnumber: (`floatnumber` | `digitpart`) ("j" | "J") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 868 | |
| 869 | An imaginary literal yields a complex number with a real part of 0.0. Complex |
| 870 | numbers are represented as a pair of floating point numbers and have the same |
| 871 | restrictions on their range. To create a complex number with a nonzero real |
| 872 | part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of |
| 873 | imaginary literals:: |
| 874 | |
Brett Cannon | a721aba | 2016-09-09 14:57:09 -0700 | [diff] [blame] | 875 | 3.14j 10.j 10j .001j 1e100j 3.14e-10j 3.14_15_93j |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 876 | |
| 877 | |
| 878 | .. _operators: |
| 879 | |
| 880 | Operators |
| 881 | ========= |
| 882 | |
| 883 | .. index:: single: operators |
| 884 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 885 | The following tokens are operators: |
| 886 | |
| 887 | .. code-block:: none |
| 888 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 889 | |
Benjamin Peterson | bd59241 | 2014-08-06 22:50:30 -0700 | [diff] [blame] | 890 | + - * ** / // % @ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 891 | << >> & | ^ ~ |
| 892 | < > <= >= == != |
| 893 | |
| 894 | |
| 895 | .. _delimiters: |
| 896 | |
| 897 | Delimiters |
| 898 | ========== |
| 899 | |
| 900 | .. index:: single: delimiters |
| 901 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 902 | The following tokens serve as delimiters in the grammar: |
| 903 | |
| 904 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 905 | |
Georg Brandl | 0df7979 | 2008-10-04 18:33:26 +0000 | [diff] [blame] | 906 | ( ) [ ] { } |
Georg Brandl | 97f9623 | 2013-10-08 21:28:22 +0200 | [diff] [blame] | 907 | , : . ; @ = -> |
Benjamin Peterson | bd59241 | 2014-08-06 22:50:30 -0700 | [diff] [blame] | 908 | += -= *= /= //= %= @= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 909 | &= |= ^= >>= <<= **= |
| 910 | |
| 911 | The period can also occur in floating-point and imaginary literals. A sequence |
Georg Brandl | 57e3b68 | 2007-08-31 08:07:45 +0000 | [diff] [blame] | 912 | of three periods has a special meaning as an ellipsis literal. The second half |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 913 | of the list, the augmented assignment operators, serve lexically as delimiters, |
| 914 | but also perform an operation. |
| 915 | |
| 916 | The following printing ASCII characters have special meaning as part of other |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 917 | tokens or are otherwise significant to the lexical analyzer: |
| 918 | |
| 919 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 920 | |
| 921 | ' " # \ |
| 922 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 923 | The following printing ASCII characters are not used in Python. Their |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 924 | occurrence outside string literals and comments is an unconditional error: |
| 925 | |
| 926 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 927 | |
Georg Brandl | e43baab | 2010-05-10 21:17:00 +0000 | [diff] [blame] | 928 | $ ? ` |
Ezio Melotti | 931b8aa | 2011-10-21 21:57:36 +0300 | [diff] [blame] | 929 | |
| 930 | |
| 931 | .. rubric:: Footnotes |
| 932 | |
Benjamin Peterson | 7c69c1c | 2018-06-06 20:14:28 -0700 | [diff] [blame] | 933 | .. [#] http://www.unicode.org/Public/11.0.0/ucd/NameAliases.txt |