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 "<stdin>", line 1
  'that's not going to work'
  ^
 SyntaxError: invalid syntax

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.

One simple way to fix this is to use double quotes around the string; we 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 quote in one string? You could do this:

 >>>​​ ​​'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 we’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 normally 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 4. Escape Sequences

Escape Sequence

Description

Single quote

"

Double quote

\

Backslash

Tab

Newline

Carriage return


In order to see how they are used, we will introduce multiline strings and also revisit built-in function print.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.146.155