Как экранировать кавычки в python
Перейти к содержимому

Как экранировать кавычки в python

  • автор:

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 14.0.0 can be found at https://www.unicode.org/Public/14.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 escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

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:

Строки — Основы Python

В этом уроке мы разберемся, что такое строка и какую роль в коде играют кавычки. Мы познакомимся со специальными символами и научимся их применять.

Определить строку довольно просто — это некий набор символов. Представим, что у нас есть такие записи:

Какие из этих вариантов — строки? На самом деле, все пять вариантов подходят:

  • С 'Hello' и 'Goodbye' все очевидно — мы уже работали с подобными конструкциями и называли их строками
  • 'G' и ' ' — тоже строки, просто в них всего по одному символу
  • '' — это пустая строка, потому что в ней ноль символов

Кавычки

Строкой мы считаем все, что находится внутри кавычек: даже если это пробел, один символ или вообще отсутствие символов.

Выше мы записывали строки в одинарных кавычках, но это не единственный способ. Можно использовать и двойные:

Теперь представьте, что вы хотите напечатать строчку Dragon's mother. Апостроф перед буквой s — это такой же символ, как одинарная кавычка. Попробуем:

Такая программа не будет работать. С точки зрения Python, строчка началась с одинарной кавычки, а потом закончилась после слова Dragon. Дальше были символы s mother без кавычек — значит, это не строка. А потом была одна открывающая строку кавычка, которая так и не закрылась: ') . Этот код содержит синтаксическую ошибку — это видно даже по тому, как подсвечен код.

Чтобы избежать этой ошибки, мы используем двойные кавычки. Такой вариант программы сработает верно:

Теперь интерпретатор знает, что строка началась с двойной кавычки и закончиться должна тоже на двойной кавычке. А одинарная кавычка внутри стала частью строки.

Верно и обратное. Если внутри строки мы хотим использовать двойные кавычки, то саму строку нужно заключать в одинарные. Причем количество кавычек внутри самой строки неважно.

Теперь представим, что мы хотим создать такую строку:

В ней есть и одинарные, и двойные кавычки. Нам нужно каким-то образом указать интерпретатору, что кавычки — это символы внутри строки, а не начало или конец строки.

Для этого используют символ экранирования: \ — обратный слэш. Если мы поставим \ перед кавычкой (одинарной или двойной), то интерпретатор распознает кавычку как обычный символ внутри строки, а не начало или конец строки:

Обратите внимание, что в примере выше нам не пришлось экранировать одинарную кавычку (апостроф 's), потому что сама строка создана с двойными кавычками. Если бы строка создавалась с одинарными кавычками, то символ экранирования нужен был бы перед апострофом, но не перед двойными кавычками.

Если нужно вывести сам обратный слеш, то работает такое же правило. Как и любой другой специальный символ, его надо экранировать:

Экранированные последовательности

Мы хотим показать вот такой диалог:

Попробуем вывести на экран строку с таким текстом:

Как видите, результат получился не такой, как мы хотели. Строки расположились друг за другом, а не одна ниже другой. Нам нужно как-то сказать интерпретатору «нажать на Enter» — сделать перевод строки после вопросительного знака. Это можно сделать с помощью символа \n :

\n — это пример экранированной последовательности (escape sequence). Такие последовательности еще называют управляющими конструкциями. Их нельзя увидеть в том же виде, в котором их набрали.

Набирая текст в Word, вы нажимаете на Enter в конце строчки. Редактор при этом ставит в конец строчки специальный невидимый символ, который называется LINE FEED (LF, перевод строчки). В некоторых редакторах можно даже включить отображение невидимых символов. Тогда текст будет выглядеть примерно так:

Устройство, которое выводит соответствующий текст, учитывает этот символ. Например, принтер при встрече с LF протаскивает бумагу вверх на одну строку, а текстовый редактор переносит весь последующий текст ниже, также на одну строку.

Существует несколько десятков таких невидимых символов, но в программировании часто встречаются всего несколько. Кроме перевода строки, к таким символам относятся:

  • табуляция \t — разрыв, который получается при нажатии на кнопку Tab
  • возврат каретки \r — работает только в Windows

Распознать такую управляющую конструкцию в тексте можно по символу \ . Программисты часто используют перевод строки \n , чтобы правильно форматировать текст. Например, напишем такой код:

Тогда на экран выведется:

Когда работаете с символом перевода, учитывайте следующие моменты:

Не важно, что стоит перед или после \n : символ или пустая строка. Перевод обнаружится и выполнится в любом случае

Строка может содержать только \n :

Программа выведет на экран:

В коде последовательность \n выглядит как два символа, но с точки зрения интерпретатора — это один специальный символ

Если нужно вывести \n как текст (два отдельных печатных символа), то можно воспользоваться экранированием — добавить еще один \ в начале. Последовательность \\n отобразится как символы \ и n , которые идут друг за другом:

В Windows для перевода строк по умолчанию используется \r\n . Такая комбинация хорошо работает только в Windows, но создает проблемы при переносе в другие системы. Например, когда в команде разработчиков есть пользователи Linux.

Дело в том, что последовательность \r\n имеет разную трактовку в зависимости от выбранной кодировки, о чем мы поговорим позже. По этой причине в среде разработчиков принято всегда использовать \n без \r .

В таком случае перевод строки всегда трактуется одинаково и отлично работает в любой системе. Не забудьте настроить ваш редактор на использование \n .

Конкатенация

В веб-разработке программы постоянно оперируют строками. Все, что мы видим на сайтах, так или иначе представлено в виде текста. Этот текст чаще всего динамический — то есть он получается из разных частей, которые соединяются вместе.

Чтобы соединить строки, нужно выполнить конкатенацию:

Склеивание строк всегда происходит в том же порядке, в котором записаны операнды. Левый операнд становится левой частью строки, а правый — правой. Вот еще несколько примеров:

Как видите, строки можно склеивать, даже если их записали с разными кавычками.

Пробел — такой же символ, как и другие, поэтому сколько пробелов поставите в строке, столько и получится в итоговой строке:

Есть ли в python функция экранирования кавычек?

нашёл тут похожую проблему Как экранировать все спецсимволы в строке? но .encode(‘string-escape’) не распознаётся, а shlex.quote делает не то.

Оно, в принципе, просто пишется, но решил спросить прежде, чем велосипеды конструировать, может есть что-то стандартное в языке для этого.

Нужно для корректного экспорта в PostgreSQL. т.е. у меня Where-Statement строится в python, потом в Delphi соединяется с основным запросом и отправляется в BD. Если параметры содержат апострофы, начинаются проблемы. Парсить весь ответ в Delphi тоже не хотелось бы, проще сразу от phyton получать в правильном виде

Python: Кавычки

В этом уроке мы разберемся, что такое строка и какую роль в коде играют кавычки.

Определить строку довольно просто — это некий набор символов. Представим, что у нас есть такие записи:

Какие из этих вариантов — строки? На самом деле, все пять вариантов подходят:

  • С 'Hello' и 'Goodbye' все очевидно — мы уже работали с подобными конструкциями и называли их строками
  • 'G' и ' ' — тоже строки, просто в них всего по одному символу
  • '' — это пустая строка, потому в ней ноль символов

Строкой мы считаем все, что находится внутри кавычек: даже если это пробел, один символ или вообще отсутствие символов.

Выше мы записывали строки в одинарных кавычках, но это не единственный способ. Можно использовать и двойные:

Теперь представьте, что вы хотите напечатать строчку Dragon's mother. Апостроф перед буквой s — это такой же символ, как одинарная кавычка. Попробуем:

Такая программа не будет работать. С точки зрения Python строчка началась с одинарной кавычки, а потом закончилась после слова dragon. Дальше были символы s mother без кавычек — значит, это не строка. А потом была одна открывающая строку кавычка, которая так и не закрылась: ') . Этот код содержит синтаксическую ошибку — это видно даже по тому, как подсвечен код.

Чтобы избежать этой ошибки, мы используем двойные кавычки. Такой вариант программы сработает верно:

Теперь интерпретатор знает, что строка началась с двойной кавычки и закончиться должна тоже на двойной кавычке. А одинарная кавычка внутри стала частью строки.

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

Теперь представим, что мы хотим создать такую строку:

В ней есть и одинарные, и двойные кавычки. Нам нужно каким-то образом указать интерпретатору, что кавычки — это один из символов внутри строки, а не начало или конец строки.

Для этого используют символ экранирования: \ — обратный слэш. Если мы поставим \ перед кавычкой (одинарной или двойной), то интерпретатор распознает кавычку как обычный символ внутри строки, а не начало или конец строки:

Обратите внимание, что в примере выше нам не пришлось экранировать одинарную кавычку (апостроф 's), потому что сама строка создана с двойными кавычками. Если бы строка создавалась с одинарными кавычками, то символ экранирования нужен был бы перед апострофом, но не перед двойными кавычками.

Если нужно вывести сам обратный слеш, то работает такое же правило. Как и любой другой специальный символ, его надо экранировать:

Задание

Напишите программу, которая выведет на экран:

Программа должна вывести на экран эту фразу в точности. Обратите внимание на кавычки в начале и в конце фразы:

Если вы зашли в тупик, то самое время задать вопрос в «Обсуждениях». Как правильно задать вопрос:

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

Тесты устроены таким образом, что они проверяют решение разными способами и на разных данных. Часто решение работает с одними входными данными, но не работает с другими. Чтобы разобраться с этим моментом, изучите вкладку «Тесты» и внимательно посмотрите на вывод ошибок, в котором есть подсказки.

Это нормально ��, в программировании одну задачу можно выполнить множеством способов. Если ваш код прошел проверку, то он соответствует условиям задачи.

В редких случаях бывает, что решение подогнано под тесты, но это видно сразу.

Создавать обучающие материалы, понятные для всех без исключения, довольно сложно. Мы очень стараемся, но всегда есть что улучшать. Если вы встретили материал, который вам непонятен, опишите проблему в «Обсуждениях». Идеально, если вы сформулируете непонятные моменты в виде вопросов. Обычно нам нужно несколько дней для внесения правок.

Кстати, вы тоже можете участвовать в улучшении курсов: внизу есть ссылка на исходный код уроков, который можно править прямо из браузера.

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

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