next up previous contents
Next: Unicode Strings Up: String Data Previous: String Constants   Contents

Special Characters and Raw Strings

Inside of any of the pairs of quotes described in the previous section, there are special character sequences, beginning with a backslash (\), which are interpreted in a special way. Table 2.1 lists these characters.

Table 2.1: Special Characters in Strings
Sequence Meaning Sequence Meaning
\ continuation \\ literal backslash
\' single quote \" double quote
\a bell \b backspace
\e escape character \0 null terminator
\n newline \t horizontal tab
\f form feed \r carriage return
\0XX octal character XX \xXX hexadecimal value XX


Using a single backslash as a continuation character is an alternative to using triple quoted strings when you are construction a string constant. Thus, the following two expressions are equivalent, but most programmers prefer the convenience of not having to use backslashes which is offered by triple quotes.

threelines = 'First\
Second\
Third'

threelines = '''First
Second
Third'''

The backslashed quote symbols are useful if you need to create a string with both single and double quotes. (If you have only one kind of quotes in your string, you can simply use the other kind to surround your string, since the two types of quotes are equivalent in python.)

As Table 2.1 shows, you can produce a backslash in a string by typing two backslashes; note that only one of the backslashes will actually appear in the string when it's printed. There are certain situations (most notably when constructing regular expressions (Section 8.5)), when typing two backslashes to get a single backslash becomes tedious. Python provides what are called raw strings, in which the character sequences shown in Table 2.1 have no special meaning. To construct a raw string, precede the opening quote character with either a lowercase or uppercase ``R'' (r or R). Note, however that a backslash cannot be the very last character of a raw string. Thus, these two expressions are equivalent:

>>> print 'Here is a backslash: \\ '
Here is a backslash: \
>>> print r'Here is a backslash: \ '
Here is a backslash: \


next up previous contents
Next: Unicode Strings Up: String Data Previous: String Constants   Contents
Phil Spector 2003-11-12