The Python Language Reference / Справочник по языку Python

→Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.
0 В отличие от стандартного C, все нераспознанные последовательности экранирования оставляются в строке без изменения, т.е. бэкслеш остается в строке. (Такое поведение может быть полезно при отладке: если какая-то последовательность экранирования неправильно написана, легче определить, что результат неверный). Важно также отметить, что последовательности действующие только для строковых литералов, попадают в категорию нераспознанных для байтовых литералов.
→1. As in Standard C, up to three octal digits are accepted.
2. Unlike in Standard C, at most two hex digits are accepted.
3. In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.
4. Individual code units which form parts of a surrogate pair can be encoded using this escape sequence. Unlike in Standard C, exactly two hex digits are required.
5. Any Unicode character can be encoded this way, but characters outside the Basic Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is compiled to use 16-bit code units (the default). Individual code units which form parts of a surrogate pair can be encoded using this escape sequence.
0 1. Как и в стандартном C, принимается до трех восьмиричных знаков.
2. В отличие от стандартного C, принимается до двух 16-ричных знаков.
3. В байтовом литерале 16- и 8-ричные знаки экранирования обозначают байт с данным значением. В строковом литерале эти знаки обозначают символ Unicode с данным кодом.
4. Отдельные блоки кода, составляющие части суррогатной пары, могут быть закодированы при помощи этой последовательности экранирования. В отличие от стандартного C, требуется именно два 16-ричных знака.
5. Этим способом могут быть закодированы любые Unicode символы, но символы вне Basic Multilingual Plane (BMP) будут закодированы с помощью суррогатной пары, если Python скомпилирован под использование 16-битных блоков кода (по умолчанию). Отдельные блоки кода, составляющие части суррогатной пары, могут быть закодированы при помощи этой последовательности экранирования.
→Notes:
0 Примечания:
→Escape sequences only recognized in string literals are:
Escape Sequence Meaning Notes
\N{name} Character named name in the Unicode database
\uxxxx Character with 16-bit hex value xxxx (4)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (5)
0 Последовательности экранирования для строковых литералов:
Escape Sequence Meaning Notes
\N{name} Символ с именем name в базе Unicode
\uxxxx Символ с 16-битным hex значением xxxx (4)
\Uxxxxxxxx Символ с 32-битным hex значением xxxxxxxx (5)
→Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
Escape Sequence Meaning Notes
\newline Backslash and newline ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo (1,3)
\xhh Character with hex value hh (2,3)
0 Если нет приставки 'r' или 'R', последовательности экранирования в строках обрабатываются согласно правилам стандартного C. Существуют следующие последовательности экранирования:
Escape Sequence Meaning Notes
\newline Игнорируется бэкслеш и newline
\\ Бэкслеш (\)
\' Одинарная кавычка (')
\" Двойная кавычка (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\ooo Символ с восьмиричным значением ooo (1,3)
\xhh Символ с 16-ричным значением hh (2,3)
→In triple-quoted strings, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the string. (A “quote” is the character used to open the string, i.e. either ' or ".)
0 В строках в тройных кавычках могут присутствовать (и сохраняются как есть) неэкранированные знаки новой строки и кавычки, кроме трех неэкранированных кавычек подряд, которые завершают строку. ("Кавычка" - это символ начала строки (значения со строковым типом), т.е. ' или ".)
→Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
0 Байтовым литералам должна предшествовать приставка 'b' или 'B'. Они создают экземпляр типа bytes вместо типа str. Этот тип может содержать только символы ASCII; если численное значение превышает или равно 128, то строка должна быть экранирована.
→String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, '\U' and '\u' escapes in raw strings are not treated specially.
0 Строковые литералы могут опционально начинаться с букв 'r' или 'R'; такие строки называются "сырыми" ("raw"), и считают бэкслеш обычным символом.
В результате символы '\U' и '\u' специального значения в сырых строках не имеют.
→In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
0 Простым языком: Оба типа литералов могут быть включены в одинарные кавычки (') или двойные кавычки ("). Также они могут быть включены в группы из трех двойных или одинарных кавычек (они обычно называются строки в тройных кавычках). Символ бэкслеш (\) используется для экранирования символов, которые в других случаюх имеют особое значение, такие как знак новой строки, сам бэкслеш или кавычки.
→One syntactic restriction not indicated by these productions is that whitespace is not allowed between the stringprefix or bytesprefix and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section Encoding declarations.
0 Есть также одно синтаксическое ограничение, не отмеченное в этих условиях: знаки пробелов (пробела, табуляции, перевода страницы) не могут находится между строковой или байтовой приставкой и остальной частью литерала. Набор исходных символов определяется объявлением кодировки, по умолчанию: UTF-8, см. раздел "Объявление кодировки".
→bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B" | "br" | "Br" | "bR" | "BR"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ASCII character except "\" or newline or the quote>
longbyteschar ::= <any ASCII character except "\">
bytesescapeseq ::= "\" <any ASCII character>
0 bytesliteral ::= bytesprefix(shortbytes | longbytes)
bytesprefix ::= "b" | "B"
shortbytes ::= "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes ::= "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::= shortbyteschar | bytesescapeseq
longbytesitem ::= longbyteschar | bytesescapeseq
shortbyteschar ::= <any ascii="ascii" character="character" except="except" or="or" newline="newline" the="the" quote="quote">
longbyteschar ::= <any ascii="ascii" character="character" except="except">
bytesescapeseq ::= "\" <any ascii="ascii" character="character"></any></any></any>
→stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "R"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= &lt;any source character except "\" or newline or the quote&gt;
longstringchar ::= &lt;any source character except "\"&gt;
stringescapeseq ::= "\" &lt;any source character&gt;
0 stringliteral ::= [stringprefix](shortstring | longstring)
stringprefix ::= "r" | "R"
shortstring ::= "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring ::= "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::= shortstringchar | stringescapeseq
longstringitem ::= longstringchar | stringescapeseq
shortstringchar ::= <any source="source" character="character" except="except" or="or" newline="newline" the="the" quote="quote">
longstringchar ::= <any source="source" character="character" except="except">
stringescapeseq ::= "\" <any source="source" character="character"></any></any></any>
→2.4.1. String and Bytes literals
String literals are described by the following lexical definitions:
0 2.4.1. Строковые (String) и Байтовые (Bytes) литералы
Строковые литералы описываются следующим лексическим определением:
→2.4. Literals
Literals are notations for constant values of some built-in types.
0 2.4. Литералы
Литералы - это обозначения постоянных значений некоторых встроенных типов.
→The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.
__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library); applications should not expect to define additional names using this convention. The set of names of this class defined by Python may be extended in future versions. See section Special method names.
__*
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names).
0 Имя _ часто используется всвязи с интернационализацией, см. документацию модуля gettext для получения информации по этой договоренности.

__*__
Определенные системой имена. Эти имена определяются интерпретатором и его реализацией (включая стандартную библиотеку). Приложения не должны определять дополнительные имена использую эту форму. Набор имен этого класса, определенных в Python, может быть расширен в будущих версиях. См. раздел "Имена специальных методов".

__*
Частные имена класса. Имена этой категории, при использовании в рамках определения класса, переписываются с использованием измененной формы, чтобы избежать конфликтов имен между "частными" атрибутами базовых и производных классов. См. в разделе "Идентификаторы (Имена)".
→Note
0 Примечание:
→Not imported by from module import *. The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. See section The import statement.
0 Не импортировать с помощью from module import *. Специальный идентификатор _ используется интерактивным интерпретатором для хранения результата последнего вычисления, хранится он в модуле builtins. Не в интерактивном режиме _ не имеет специального значения, неопределен. См. раздел "Объявление импорта".
→_*
0 _*
→2.3.2. Reserved classes of identifiers
Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:
0 2.3.2. Зарезервированные классы идентификаторов
Определенные классы идентификаторов (помимо ключевых слов) имеют определенное значение. Эти классы отмечаются по шаблону: символ подчеркивания в начале и в конце.
→False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
0 False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Резюме
Пол:
мужчина
Родной язык:
украинский
С нами:
с 26 сентября 2008 г. (6597 дней)
Не является членом клуба.
Деятельность:
206 версий перевода с общим рейтингом 0
3 комментария
Карма: 1 (оценок: 1)
Написать vanderloos личное сообщение