WHAT IS TRIPLE-QUOTED STRINGS IN PYTHON PROGRAMMING

TRIPLE-QUOTED STRINGS

Earlier, we introduced strings delimited by a pair of single quotes (') or a pair of double quotes ("). Triple­quoted 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 double­quote characters:

In [1]: print('Display "hi” in quotes')
Display "hi” in quotes

but not single quotes:

In [2]: print('Display 'hi' in quotes')
File "<ipython-­input­-2­19bf596ccf72>", line 1
print('Display 'hi' in quotes')
SyntaxError
: invalid syntax

unless you use the \' escape sequence:

In [3]: print('Display \'hi\' in quotes')
Display 'hi' in quotes

Snippet [2] displayed a syntax error due to a single quote inside a single­quoted 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:

In [4]: print("Display the name O'Brien")
Display the name O'Brien

but not double quotes, unless you use the \" escape sequence:

In [5]: print("Display \"hi\” in quotes")
Display "hi” in quotes

To avoid using \' and \" inside strings, you can enclose such strings in triple quotes:

In [6]: print("""Display "hi” and 'bye' in quotes""")
Display "hi” and 'bye' in quotes

Multiline Strings

The following snippet assigns a multiline triple­quoted string to triple_quoted_string:

In [7]: triple_quoted_string = """This is a triple­-quoted
...: 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:

In [8]: print(triple_quoted_string)
This is a triple­quoted
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:

In [9]: triple_quoted_string
Out[9]: 'This is a triple­quoted\nstring that spans two lines'

*

Post a Comment (0)
Previous Post Next Post