There are many forms for string constants:
'...': You may enclose the string in
single-quotes.
"...": You may instead enclose it in
double-quotes. Internally, there is absolutely no
difference. To include a double-quote character
inside the string, use the escape sequence
“\"”.
In conversational mode, Python will generally
display values using single-quotes. If the string
contains single-quotes but no double-quotes, Python
will display the value using double-quotes. If the
string contains both, the value will be displayed
in single-quotes, with single-quote characters
inside the value displayed as the escape sequence
“\'”.
'''...''': You may enclose your
string between three single quotes in a row. The
difference is that you can continue such a string over
multiple lines, and the line breaks will be included in
the string as newline characters.
"""...""": You can use three sets of
double quotes. As with three sets of single quotes,
line breaks are allowed and preserved as "\n" characters. If you use these
triply-quoted strings in conversational mode,
continuation lines will prompt you with “... ”.
>>> 'Penguin' 'Penguin' >>> "ha'penny" "ha'penny" >>> "Single ' and double\" quotes" 'Single \' and double" quotes' >>> '' '' >>> "" '' >>> s='''This string ... contains two lines.''' >>> t="""This string ... contains ... three lines."""
In addition, you can use any of these escape sequences inside a string constant (see Wikipedia for more information on the ASCII code).
Table 2. String escape sequences
\ | A backslash at the end of a line is ignored. |
\\ | Backslash (\) |
\' | Closing single quote (') |
\" | Double-quote character (") |
\n | Newline (ASCII LF or linefeed) |
\b | Backspace (in ASCII, the BS character) |
\f | Formfeed (ASCII FF) |
\r | Carriage return (ASCII CR) |
\t | Horizontal tab (ASCII HT) |
\v | Vertical tab (ASCII VT) |
\ | The character with octal code
, e.g.,
'\177'. |
\x | The character with hexadecimal value
, e.g.,
'\xFF'. |
Raw strings: If you need to use a lot
of backslashes inside a string constant, and doubling them
is too confusing, you can prefix any string with the letter
r to suppress the interpretation of escape
sequences. For example, '\\\\' contains two
backslashes, but r'\\\\' contains four. Raw
strings are particularly useful with Section 28.5, “re: Regular expression
pattern-matching”.