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.
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" % ("a", "b")
a...b
And now, without further delay, here’s the script you’ve all been waiting for (drum roll please)—the hello world program in Python. Alas, it’s more than a little anticlimactic. To print a hello world message in Python, you simply print it:
>>>print 'hello world'
# print a string object hello world >>>'hello world'
# interactive prints 'hello world' >>>import sys
# printing the hard way >>>sys.stdout.write('hello world ')
hello world
Printing is as simple as it should be in Python; although you can
achieve the same effect by calling the write
method of the sys.stdout
file object, the
print
statement is provided as a simpler tool for
simple printing jobs. Since expression results are echoed in the
interactive command line, you often don’t even need to use a
print
statement there; simply type expressions
you’d like to have printed.