2. Лексичний аналіз — Python 3.15.2 documentation
Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » Довідник з мови Python » 2. Лексичний аналіз | Theme | 2. Лексичний аналіз ¶ A Python program is read by a parser . Input to the parser is a stream of tokens , generated by the lexical analyzer (also known as the tokenizer ). This chapter describes how the lexical analyzer produces these tokens.
The lexical analyzer determines the program text’s encoding (UTF-8 by default), and decodes the text into source characters . If the text cannot be decoded, a SyntaxError is raised. Next, the lexical analyzer uses the source characters to generate a stream of tokens. The type of a generated token generally depends on the next source character to be processed. Similarly, other special behavior of the analyzer depends on the first source character that hasn’t yet been processed.
The following table gives a quick summary of these source characters, with links to sections that contain more information. Character Next token (or other relevant documentation) простір tab formfeed Whitespace CR, LF New line Indentation backslash ( \ ) Explicit line joining (Also significant in string escape sequences ) hash ( # ) Comment quote ( ' , " ) String literal ASCII letter ( a - z , A - Z ) non-ASCII character Name Prefixed string or bytes literal underscore ( _ ) Name (Can also be part of numeric literals ) number ( 0 - 9 ) Numeric literal dot ( . ) Numeric literal Operator question mark ( ? ) dollar ( $ ) backquote ( ` ) control character Error (outside string literals and comments) other printing character Operator or delimiter end of file End marker 2.1.
Лінійна структура ¶ Програма Python розділена на кілька логічних рядків . 2.1.1. Логічні лінії ¶ The end of a logical line is represented by the token NEWLINE . Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.
2.1.2. Фізичні лінії ¶ A physical line is a sequence of characters terminated by one the following end-of-line sequences: the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), the „ Classic Mac OS “ form using the ASCII CR (return) character. Regardless of platform, each of these sequences is replaced by a single ASCII LF (linefeed) character. (This is done even inside string literals .) Each line can use any of the sequences; they do not need to be consistent within a file.
The end of input also serves as an implicit terminator for the final physical line. Formally: newline : <ASCII LF> | <ASCII CR> <ASCII LF> | <ASCII CR> 2.1.3. Коментарі ¶ Коментар починається з символу решетки ( # ), який не є частиною рядкового літералу, і закінчується в кінці фізичного рядка. Коментар означає кінець логічного рядка, якщо не викликаються неявні правила з’єднання рядків.
Коментарі ігноруються синтаксисом. 2.1.4. Оголошення кодування ¶ Якщо коментар у першому чи другому рядку сценарію Python відповідає регулярному виразу coding[=:]\s*([-\w.]+) , цей коментар обробляється як оголошення кодування; перша група цього виразу називає кодування файлу вихідного коду.
Оголошення кодування має з’являтися в окремому рядку. Якщо це другий рядок, перший рядок також має бути рядком лише для коментарів. Рекомендовані форми виразу кодування: # -*- coding: <encoding-name> -*- який також розпізнається GNU Emacs і # vim:fileencoding=<encoding-name> який розпізнається VIM Брема Муленаара.
If no encoding declaration is found, the default encoding is UTF-8. If the implicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-order mark ( b'\xef\xbb\xbf' ) is ignored rather than being a syntax error. Якщо оголошено кодування, Python має розпізнавати назву кодування (див. Стандартні кодування ). Кодування використовується для всього лексичного аналізу, включаючи рядкові літерали, коментарі та ідентифікатори.
All lexical analysis, including string literals, comments and identifiers, works on Unicode text decoded using the source encoding. Any Unicode code point, except the NUL control character, can appear in Python source. source_character : <any Unicode code point, except NUL> 2.1.5. Явне з’єднання рядків ¶ Два або більше фізичних рядків можна об’єднати в логічні рядки за допомогою символів зворотної похилої риски ( \ ), таким чином: коли фізичний рядок закінчується зворотною похилою рискою, яка не є частиною рядкового літералу чи коментаря, він об’єднується за допомогою наступного: утворюючи один логічний рядок, видаляючи зворотну косу риску та наступний символ кінця рядка.
Наприклад: if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60 : # Looks like a valid date return 1 Рядок, який закінчується зворотною скісною рискою, не може містити коментаря. Зворотна коса риска не продовжує коментар. Зворотний слеш не продовжує лексему, за винятком рядкових літералів (тобто лексеми, окрім рядкових літералів, не можна розділити на фізичні рядки за допомогою зворотної похилої риски).
Зворотний слеш неприпустимий в іншому місці рядка за межами рядкового літералу. 2.1.6. Неявне з’єднання ліній ¶ Вирази в дужках, квадратних або фігурних дужках можна розділити на кілька фізичних рядків без використання зворотних скісних риск.
Наприклад: month_names = [ 'Januari' , 'Februari' , 'Maart' , # These are the 'April' , 'Mei' , 'Juni' , # Dutch names 'Juli' , 'Augustus' , 'September' , # for the months 'Oktober' , 'November' , 'December' ] # of the year Неявно продовжені рядки можуть містити коментарі. Відступ рядків продовження не важливий. Допускаються порожні рядки продовження.
Немає маркера NEWLINE між рядками неявного продовження. Неявно продовжені рядки також можуть зустрічатися в рядках із потрійними лапками (див. нижче); у цьому випадку в�
The rest of this page is on the live site.