Next / Previous / Contents / TCC Help System / NM Tech homepage

9.1. String constants

There are many forms for string constants:

>>> '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

\newlineA backslash at the end of a line is ignored.
\\Backslash (\)
\'Closing single quote (')
\"Double-quote character (")
\nNewline (ASCII LF or linefeed)
\bBackspace (in ASCII, the BS character)
\fFormfeed (ASCII FF)
\rCarriage return (ASCII CR)
\tHorizontal tab (ASCII HT)
\vVertical tab (ASCII VT)
\oooThe character with octal code ooo, e.g., '\177'.
\xhhThe character with hexadecimal value hh, 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”.