FUNCTION PRINT AND AN INTRO TO SINGLE- AND DOUBLE-QUOTED STRINGS
The builtin print function displays its argument(s) as a line of text:
Welcome to Python!
In this case, the argument 'Welcome to Python!' is a string—a sequence of characters enclosed in single quotes ('). Unlike when you evaluate expressions in interactive mode, the text that print displays here is not preceded by Out[1]. Also, print does not display a string’s quotes, though we’ll soon show how to display quotes in strings.
You also may enclose a string in double quotes ("), as in:
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
The print function can receive a commaseparated list of arguments, as in:
Welcome to Python!
It displays each argument separated from the next by a space, producing the same output as in the two preceding snippets. Here we showed a commaseparated list of strings, but the values can be of any type. We’ll show in the next chapter how to prevent automatic spacing between values or use a different separator than space.
Printing Many Lines of Text with One Statement
When a backslash (\) appears in a string, it’s known as the escape character. The backslash and the character immediately following it form an escape sequence. For example, \n represents the newline character escape sequence, which tells print to move the output cursor to the next line. The following snippet uses three newline characters to create several lines of output:i
Welcome
to
Python!
| 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
You may also 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:
...: split it over two lines')
this is a longer string, so we split it over two lines
The interpreter reassembles the string’s parts into a single string with no line break. Though the backslash character in the preceding snippet is inside a string, it’s not the escape character because another character does not follow it.
Printing the Value of an Expression
Calculations can be performed in print statements:
Sum is 10