2.4 Function print and an Intro to Single-and-Double-Quoted Strings

  • The built-in print function displays its argument(s) as a line of text
In [1]:
print('Welcome to Python!')
Welcome to Python!
  • May enclose a string in double quotes (").
In [2]:
print("Welcome to Python!")
Welcome to Python!
  • Python programmers generally prefer single quotes.
  • When print completes its task, it positions the screen cursor at the beginning of the next line.

Printing a Comma-Separated List of Items

In [3]:
print('Welcome', 'to', 'Python!')
Welcome to Python!
  • Displays each argument separated from the next by a space.

Printing Many Lines of Text with One Statement

  • A backslash (\) in a string is the escape character.
  • The backslash and the character immediately following it form an escape sequence.
  • \n represents the newline character escape sequence, which tells print to move the output cursor to the next line.
In [4]:
print('Welcome\nto\n\nPython!')
Welcome
to

Python!

Other Escape Sequences

Escape sequence Description
\n Insert a newline character in a string. When the string is displayed, for each newline, move the screen cursor to the beginning of the next line.
\t Insert a horizontal tab. When the string is displayed, for each tab, move the screen cursor to the next tab stop.
\\ Insert a backslash character in a string.
\" Insert a double quote character in a string.
\' Insert a single quote character in a string.

Ignoring a Line Break in a Long String

  • Can split a long string (or a long statement) over several lines by using the \ continuation character as the last character on a line to ignore the line break.
In [5]:
print('this is a longer string, so we \
split it over two lines')
this is a longer string, so we split it over two lines
  • In this case, \ is not the escape character because another character does not follow it.

Printing the Value of an Expression

In [6]:
print('Sum is', 7 + 3)
Sum is 10

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