Экранирование python что это

Работа со строками в Python: литералы

Строки в Python — упорядоченные последовательности символов, используемые для хранения и представления текстовой информации, поэтому с помощью строк можно работать со всем, что может быть представлено в текстовой форме.

Это первая часть о работе со строками, а именно о литералах строк.

Литералы строк

Работа со строками в Python очень удобна. Существует несколько литералов строк, которые мы сейчас и рассмотрим.

Строки в апострофах и в кавычках

Строки в апострофах и в кавычках — одно и то же. Причина наличия двух вариантов в том, чтобы позволить вставлять в литералы строк символы кавычек или апострофов, не используя экранирование.

Экранированные последовательности — служебные символы

Экранированные последовательности позволяют вставить символы, которые сложно ввести с клавиатуры.

Экранированная последовательность Назначение
\n Перевод строки
\a Звонок
\b Забой
\f Перевод страницы
\r Возврат каретки
\t Горизонтальная табуляция
\v Вертикальная табуляция
\N Идентификатор ID базы данных Юникода
\uhhhh 16-битовый символ Юникода в 16-ричном представлении
\Uhhhh… 32-битовый символ Юникода в 32-ричном представлении
\xhh 16-ричное значение символа
\ooo 8-ричное значение символа
\0 Символ Null (не является признаком конца строки)

«Сырые» строки — подавляют экранирование

Если перед открывающей кавычкой стоит символ ‘r’ (в любом регистре), то механизм экранирования отключается.

Но, несмотря на назначение, «сырая» строка не может заканчиваться символом обратного слэша. Пути решения:

Строки в тройных апострофах или кавычках

Главное достоинство строк в тройных кавычках в том, что их можно использовать для записи многострочных блоков текста. Внутри такой строки возможно присутствие кавычек и апострофов, главное, чтобы не было трех кавычек подряд.

Это все о литералах строк и работе с ними. О функциях и методах строк я расскажу в следующей статье.

Строки¶

Строки в Python — упорядоченные последовательности символов, используемые для хранения и представления текстовой информации, поэтому с помощью строк можно работать со всем, что может быть представлено в текстовой форме.

Литералы строк¶

Работа со строками в Python очень удобна. Существует несколько литералов строк, которые мы сейчас и рассмотрим.

Строки в апострофах и в кавычках¶

Строки в апострофах и в кавычках — одно и то же. Причина наличия двух вариантов в том, чтобы позволить вставлять в литералы строк символы кавычек или апострофов, не используя экранирование.

Служебные символы¶

Экранированные последовательности позволяют вставить символы, которые сложно ввести с клавиатуры.

Экранированная последовательность Назначение
\n Перевод строки
\a Звонок
\b Забой
\f Перевод страницы
\r Возврат каретки
\t Горизонтальная табуляция
\v Вертикальная табуляция
\N Идентификатор ID базы данных Юникода
\uhhhh 16-битовый символ Юникода в 16-ричном представлении
\Uhhhh… 32-битовый символ Юникода в 32-ричном представлении
\xhh 16-ричное значение символа
\ooo 8-ричное значение символа
\0 Символ Null (не является признаком конца строки)

«Сырые» строки¶

Если перед открывающей кавычкой стоит символ r (в любом регистре), то механизм экранирования отключается.

Но, несмотря на назначение, «сырая» строка не может заканчиваться символом обратного слэша. Пути решения:

Строки в тройных апострофах или кавычках¶

Главное достоинство строк в тройных кавычках в том, что их можно использовать для записи многострочных блоков текста. Внутри такой строки возможно присутствие кавычек и апострофов, главное, чтобы не было трех кавычек подряд.

Функции и методы строк¶

Конкатенация (сложение)¶

Дублирование строки¶

Длина строки (функция len)¶

Доступ по индексу¶

Как видно из примера, в Python возможен и доступ по отрицательному индексу, при этом отсчет идет от конца строки.

Извлечение среза¶

Оператор извлечения среза: [X:Y] . X – начало среза, а Y – окончание;

символ с номером Y в срез не входит. По умолчанию первый индекс равен 0 , а второй — длине строки.

Кроме того, можно задать шаг, с которым нужно извлекать срез.

Другие функции и методы строк¶

При вызове методов необходимо помнить, что строки в Python относятся к категории неизменяемых последовательностей, то есть все функции и методы могут лишь создавать новую строку.

Поэтому все строковые методы возвращают новую строку, которую потом следует присвоить переменной.

Функция или метод Назначение
S = ‘str’; S = «str»; S = »’str»’; S = «»»str»»» Литералы строк
S = «s\np\ta\nbbb» Экранированные последовательности
S = r»C:\temp\new» Неформатированные строки (подавляют экранирование)
S = b»byte» Строка байтов
S1 + S2 Конкатенация (сложение строк)
S1 * 3 Повторение строки
S[i] Обращение по индексу
S[i:j:step] Извлечение среза
len(S) Длина строки
S.find(str, [start],[end]) Поиск подстроки в строке. Возвращает номер первого вхождения или -1
S.rfind(str, [start],[end]) Поиск подстроки в строке. Возвращает номер последнего вхождения или -1
S.index(str, [start],[end]) Поиск подстроки в строке. Возвращает номер первого вхождения или вызывает ValueError
S.rindex(str, [start],[end]) Поиск подстроки в строке. Возвращает номер последнего вхождения или вызывает ValueError
S.replace(шаблон, замена[, maxcount]) Замена шаблона на замену. maxcount ограничивает количество замен
S.split(символ) Разбиение строки по разделителю
S.isdigit() Состоит ли строка из цифр
S.isalpha() Состоит ли строка из букв
S.isalnum() Состоит ли строка из цифр или букв
S.islower() Состоит ли строка из символов в нижнем регистре
S.isupper() Состоит ли строка из символов в верхнем регистре
S.isspace() Состоит ли строка из неотображаемых символов (пробел, символ перевода страницы ( \f ), «новая строка» ( \n ), «перевод каретки» ( \r ), «горизонтальная табуляция» ( \t ) и «вертикальная табуляция» ( \v ))
S.istitle() Начинаются ли слова в строке с заглавной буквы
S.upper() Преобразование строки к верхнему регистру
S.lower() Преобразование строки к нижнему регистру
S.startswith(str) Начинается ли строка S с шаблона str
S.endswith(str) Заканчивается ли строка S шаблоном str
S.join(список) Сборка строки из списка с разделителем S
ord(символ) Символ в его код ASCII
chr(число) Код ASCII в символ
S.capitalize() Переводит первый символ строки в верхний регистр, а все остальные в нижний
S.center(width, [fill]) Возвращает отцентрованную строку, по краям которой стоит символ fill (пробел по умолчанию)
S.count(str, [start],[end]) Возвращает количество непересекающихся вхождений подстроки в диапазоне [начало, конец] ( 0 и длина строки по умолчанию)
S.expandtabs([tabsize]) Возвращает копию строки, в которой все символы табуляции заменяются одним или несколькими пробелами, в зависимости от текущего столбца. Если TabSize не указан, размер табуляции полагается равным 8 пробелам
S.lstrip([chars]) Удаление пробельных символов в начале строки
S.rstrip([chars]) Удаление пробельных символов в конце строки
S.strip([chars]) Удаление пробельных символов в начале и в конце строки
S.partition(шаблон) Возвращает кортеж, содержащий часть перед первым шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий саму строку, а затем две пустых строки
S.rpartition(sep) Возвращает кортеж, содержащий часть перед последним шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий две пустых строки, а затем саму строку
S.swapcase() Переводит символы нижнего регистра в верхний, а верхнего – в нижний
S.title() Первую букву каждого слова переводит в верхний регистр, а все остальные в нижний
S.zfill(width) Делает длину строки не меньшей width , по необходимости заполняя первые символы нулями
S.ljust(width, fillchar=» «) Делает длину строки не меньшей width , по необходимости заполняя последние символы символом fillchar
S.rjust(width, fillchar=» «) Делает длину строки не меньшей width , по необходимости заполняя первые символы символом fillchar
S.format(*args, **kwargs) Форматирование строки

Форматирование строк¶

Иногда (а точнее, довольно часто) возникают ситуации, когда нужно сделать строку, подставив в неё некоторые данные, полученные в процессе выполнения программы (пользовательский ввод, данные из файлов и т. д.). Подстановку данных можно сделать с помощью форматирования строк. Форматирование можно сделать с помощью оператора % , либо с помощью метода format .

Если для подстановки требуется только один аргумент, то значение — сам аргумент:

А если несколько, то значениями будут являться все аргументы со строками подстановки (обычных или именованных):

Однако метод format умеет большее. Вот его синтаксис:

Теперь спецификация формата:

Выравнивание производится при помощи символа-заполнителя. Доступны следующие варианты выравнивания:

Флаг Значение
< Символы-заполнители будут справа (выравнивание объекта по левому краю) (по умолчанию).
> выравнивание объекта по правому краю.
= Заполнитель будет после знака, но перед цифрами. Работает только с числовыми типами.
^ Выравнивание по центру.

Опция «знак» используется только для чисел и может принимать следующие значения:

2. Lexical analysis¶

A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens.

Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details. If the source file cannot be decoded, a SyntaxError is raised.

2.1. Line structure¶

A Python program is divided into a number of logical lines.

2.1.1. Logical lines¶

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. Physical lines¶

A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used — the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line.

When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the \n character, representing ASCII LF, is the line terminator).

2.1.3. Comments¶

A comment starts with a hash character ( # ) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax.

2.1.4. Encoding declarations¶

If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+) , this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line. The recommended forms of an encoding expression are

which is recognized also by GNU Emacs, and

which is recognized by Bram Moolenaar’s VIM.

If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark ( b’\xef\xbb\xbf’ ), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s notepad).

If an encoding is declared, the encoding name must be recognized by Python (see Standard Encodings ). The encoding is used for all lexical analysis, including string literals, comments and identifiers.

2.1.5. Explicit line joining¶

Two or more physical lines may be joined into logical lines using backslash characters ( \ ), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

2.1.6. Implicit line joining¶

Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:

Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.

2.1.7. Blank lines¶

A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.

2.1.8. Indentation¶

Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level.

A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).

The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.

Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.

Here is an example of a correctly (though confusingly) indented piece of Python code:

The following example shows various indentation errors:

(Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of return r does not match a level popped off the stack.)

2.1.9. Whitespace between tokens¶

Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).

2.2. Other tokens¶

Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token, when read from left to right.

2.3. Identifiers and keywords¶

Identifiers (also referred to as names) are described by the following lexical definitions.

The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details.

Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z , the underscore _ and, except for the first character, the digits 0 through 9 .

Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.

Identifiers are unlimited in length. Case is significant.

The Unicode category codes mentioned above stand for:

Lu — uppercase letters

Ll — lowercase letters

Lt — titlecase letters

Lm — modifier letters

Lo — other letters

Nl — letter numbers

Mn — nonspacing marks

Mc — spacing combining marks

Nd — decimal numbers

Pc — connector punctuations

Other_ID_Start — explicit list of characters in PropList.txt to support backwards compatibility

All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.

A non-normative HTML file listing all valid identifier characters for Unicode 4.1 can be found at https://www.unicode.org/Public/13.0.0/ucd/DerivedCoreProperties.txt

2.3.1. Keywords¶

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

2.3.2. Soft Keywords¶

New in version 3.10.

Some identifiers are only reserved under specific contexts. These are known as soft keywords. The identifiers match , case and _ can syntactically act as keywords in contexts related to the pattern matching statement, but this distinction is done at the parser level, not when tokenizing.

As soft keywords, their use with pattern matching is possible while still preserving compatibility with existing code that uses match , case and _ as identifier names.

2.3.3. 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:

Not imported by from module import * .

In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard .

Separately, the interactive interpreter makes the result of the last evaluation available in the variable _ . (It is stored in the builtins module, alongside built-in functions like print .)

Elsewhere, _ is a regular identifier. It is often used to name “special” items, but it is not special to Python itself.

The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.

It is also commonly used for unused variables.

System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

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) .

2.4. Literals¶

Literals are notations for constant values of some built-in types.

2.4.1. String and Bytes literals¶

String literals are described by the following lexical definitions:

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 .

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 give special meaning to otherwise ordinary characters like n , which means ‘newline’ when escaped ( \n ). It can also be used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. See escape sequences below for examples.

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.

Both string and bytes 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, in string literals, ‘\U’ and ‘\u’ escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the ‘ur’ syntax is not supported.

New in version 3.3: The ‘rb’ prefix of raw bytes literals has been added as a synonym of ‘br’ .

New in version 3.3: Support for the unicode legacy literal ( u’value’ ) was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.

A string literal with ‘f’ or ‘F’ in its prefix is a formatted string literal; see Formatted string literals . The ‘f’ may be combined with ‘r’ , but not with ‘b’ or ‘u’ , therefore raw formatted strings are possible, but formatted bytes literals are not.

In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either ‘ or " .)

Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:

Артём Саннников

Допустим, вам по какой-то причине нужно разместить двойные кавычки внутри двойных кавычек. Как же это сделать? Всё довольно просто, есть метод ,который называется — экранирование.

Экранирование (\) — это метод, который отменяет действие кавычек и переводит их в обычную последовательность символов и теперь они воспринимаются, как часть текста. Чтобы применить экранирование, нужно воспользоваться символом — обратный слэш (\).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *