Ways to escape

To tell Python to give special treatment to a character in a string literal, precede it with a backslash character (\), also called the escape character.

Table 6-1 lists some of the characters that do special things when preceded by a backslash. (These are commonly called escape codes.)

Table 6-1: Some Python Escape Codes ■=>Open table as spreadsheet

Character

Meaning

\ as last character on a line

Text on the next line goes with the text on this line.

\\

Backslash

\'

Single quote

\"

Double quote

\e

Escape key

\n

Linefeed

\t

Tab

\0 nn

Octal character (nn is a two-digit number)

\x nn

Hexadecimal character (nn is a two-digit number)

One way to use the backslash is to tell Python to treat a quotation mark as a regular character rather than as a "string starter or ender," as in this example:

>>> whiteRabbit = 'Where\'s my pocket-watch?' >>> print whiteRabbit Where's my pocket-watch?

Tip It's easier to read strings that don't have escape characters within the code, so avoid them if you can. If you have text with both single and double quotes, consider using triple quotes to designate it as a string.

To tell Python that a backslash is part of your string and not an escape character, precede it with a second backslash, as shown:

>>> path = "C:\\Applications" >>> print path C:\Applications

Was this article helpful?

0 0

Post a comment