2.5 Triple-Quoted Strings

  • Delimited by """ or ''', but the Style Guide for Python Code recommends """.
  • Used for:
    • multiline strings
    • strings containing single or double quotes
    • docstrings—the recommended way to document the purposes of certain program components.

Including Quotes in Strings (1 of 3)

  • A string delimited by single quotes may include double-quote characters, but not single quotes, unless you use the \' escape sequence.
In [1]:
print('Display "hi" in quotes')
Display "hi" in quotes
In [2]:
print('Display 'hi' in quotes')
  File "<ipython-input-2-19bf596ccf72>", line 1
    print('Display 'hi' in quotes')
                     ^
SyntaxError: invalid syntax
In [3]:
print('Display \'hi\' in quotes')
Display 'hi' in quotes

Including Quotes in Strings (2 of 3)

  • A string delimited by double quotes may include single quote characters, but not double quotes, unless you use the \" escape sequence.
In [4]:
print("Display the name O'Brien")
Display the name O'Brien
In [5]:
print("Display \"hi\" in quotes")
Display "hi" in quotes

Including Quotes in Strings (3 of 3)

  • Triple-quoted strings may contain both single and double quotes.
In [6]:
print("""Display "hi" and 'bye' in quotes""")
Display "hi" and 'bye' in quotes

Multiline Strings (1 of 2)

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.
  • 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.

Multiline Strings (2 of 2)

In [8]:
print(triple_quoted_string)
This is a triple-quoted
string that spans two lines
  • Python stores multiline strings with embedded newline characters.
In [9]:
triple_quoted_string
Out[9]:
'This is a triple-quoted\nstring that spans two lines'

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 2 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.