Книга: Practical Programming, Fourth Edition
Назад: Creating Strings of Characters
Дальше: Creating a Multiline String

Using Special Characters in Strings

Suppose you want to put a single quote inside a string. If you write it directly, an error occurs:

 >>>​​ ​​'that'​​s​​ ​​not​​ ​​going​​ ​​to​​ ​​work​​'
  File "<python-input-0>", line 1
  'that's not going to work'
  ^
 SyntaxError: unterminated string literal (detected at line 1)

When Python encounters the second quote—the one that is intended to be part of the string—it thinks the string is ended. It doesn’t know what to do with the text that comes after the second quote.

A straightforward way to fix this error is to use double quotes around the string; you can also put single quotes around a string containing a double quote:

 >>>​​ ​​"that's better"
 "that's better"
 >>>​​ ​​'She said, "That is better."'
 'She said, "That is better."'

If you need to put a double quote in a string, you can use single quotes around the string. But what if you want to put both kinds of quotes in one string? You could split the string into parts enclosed in different quotes and concatenate them:

 >>>​​ ​​'She said, "That'​​ ​​+​​ ​​"'"​​ ​​+​​ ​​'s hard to read."'
 'She said, "That\'s hard to read."'

The result is a valid Python string. The backslash is called an escape character, and the combination of the backslash and the single quote is called an escape sequence. The name comes from the fact that you’re “escaping” from Python’s usual syntax rules for a moment. When Python sees a backslash inside a string, it means that the next character represents something that Python typically uses for other purposes, such as marking the end of a string.

The escape sequence \’ is indicated using two symbols, but those two symbols represent a single character:

 >>>​​ ​​len(​​'\'​​'​​)
 1
 >>>​​ ​​len(​​'it\'​​s​​'​​)
 4

Python recognizes several escape sequences. Here are some common ones:


Table 2. Escape Sequences

Escape Sequence

Description

\’

Single quote

\"

Double quote

\\

Backslash

\t

Tab

\n

Newline/Line feed (move down to the next line)

\r

Carriage return (move to the start of the same line)


To demonstrate their use, let’s introduce multiline strings and revisit the built-in print function.

Назад: Creating Strings of Characters
Дальше: Creating a Multiline String