Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

Print

The print statement simply prints objects. Technically, it writes the textual representation of objects to the standard output stream. The standard output stream happens to be the same as the C stdout stream and usually maps to the window where you started your Python program (unless you’ve redirected it to a file in your system’s shell).

In Chapter 2, we also saw file methods that write text. The print statement is similar, but more focused: print writes objects to the stdout stream (with some default formatting), but file write methods write strings to files. Since the standard output stream is available in Python as the stdout object in the built-in sys module (aka sys.stdout), it’s possible to emulate print with file writes (see below), but print is easier to use.

Table 3.4 lists the print statement’s forms.

Table 3-4. Print Statement Forms

Operation

Interpretation

print spam, ham

Print objects to sys.stdout, add a space between

print spam, ham,

Same, but don’t add newline at end

By default, print adds a space between items separated by commas and adds a linefeed at the end of the current output line. To suppress the linefeed (so you can add more text on the same line later), end your print statement with a comma, as shown in the second line of the table. To suppress the space between items, you can instead build up an output string using the string concatenation and formatting tools in Chapter 2:

>>> print "a", "b"
a b
>>> print "a" + "b"
ab
>>> print "%s...%s" % ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata