TRIPLE-QUOTED STRINGS
Earlier, we introduced strings delimited by a pair of single quotes (') or a pair of double quotes ("). Triplequoted strings begin and end with three double quotes (""") or three single quotes ('''). The Style Guide for Python Code recommends three double quotes ("""). Use these to create:
- multiline strings,
- strings containing single or double quotes and
- docstrings, which are the recommended way to document the purposes of certain program components.
Including Quotes in Strings
In a string delimited by single quotes, you may include doublequote characters:
Display "hi” in quotes
but not single quotes:
File "<ipython-input-219bf596ccf72>", line 1
SyntaxError: invalid syntax
unless you use the \' escape sequence:
Display 'hi' in quotes
Snippet [2] displayed a syntax error due to a single quote inside a singlequoted string. IPython displays information about the line of code that caused the syntax error and points to the error with a ^ symbol. It also displays the message SyntaxError:
invalid syntax.A string delimited by double quotes may include single quote characters:
Display the name O'Brien
but not double quotes, unless you use the \" escape sequence:
Display "hi” in quotes
To avoid using \' and \" inside strings, you can enclose such strings in triple quotes:
Display "hi” and 'bye' in quotes
Multiline Strings
The following snippet assigns a multiline triplequoted string to triple_quoted_string:
...: string that spans two lines"""
IPython knows that the string is incomplete because we did not type the closing """ before we pressed Enter. So, IPython displays a continuation prompt ...: at which you can input the multiline string’s next line. This continues until you enter the ending """ and press Enter. The following displays triple_quoted_string:
This is a triplequoted
string that spans two lines
Python stores multiline strings with embedded newline characters. When we evaluate triple_quoted_string rather than printing it, IPython displays it in single quotes with a \n character where you pressed Enter in snippet [7]. The quotes IPython displays indicate that triple_quoted_string is a string—they’re not part of the string’s contents:
Out[9]: 'This is a triplequoted\nstring that spans two lines'