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 |
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" % ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.