Linux/Unix > Python Essential Reference, Second Edition > 9. Input and Output > The print Statement | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105085094125052078027057

### The `print` Statement

The `print` statement produces output on the file contained in `sys.stdout`. `print` accepts a comma-separated list of objects such as the following:

    print "The values are", x, y, z

For each object, the `str()` function is invoked to produce an output string. These output strings are then joined and separated by a single space to produce the final output string. The output is terminated by a newline unless a trailing comma is supplied to the `print` statement. In this case, only a trailing space is printed. For example:

    print "The values are ", x, y, z, w
    # Print the same text, using two print statements
    print "The values are ", x, y,   # Omits trailing newline
    print z, w

To produce formatted output, use the string-formatting operator (`%`) as described in Chapter 4, “Operators and Expressions.” For example:

    print "The values are %d %7.5f %s" % (x,y,z) # Formatted I/O

You can change the destination of the `print` statement by adding the special `>>``file` modifier, where `file` is a file object that allows writes. Here’s an example:

    f = open("output","w")
    print >>f, "hello world"
    ...
    f.close()

Combining formatted I/O using dictionaries with triple-quoted strings is a powerful way to write computer-generated text. For example, you might want to write a short form letter, filling in a `name`, an `item` name, and an `amount`, like this:

    Dear Mr. Bush,
    Please send back my blender or pay me $50.00.

                                         Sincerely yours,

                                         Joe Python User

To do this, you can form a triple-quoted string containing text and dictionary-based format specifiers such as this:

    form = """\
    Dear %(name)s,
    Please send back my %(item)s or pay me $%(amount)0.2f.

                                         Sincerely yours,

                                         Joe Python User
    """
    print form % { 'name': 'Mr. Bush',
                   'item': 'blender',
                   'amount': 50.00,
                 }

For forms involving many lines and many items to be substituted, this is much clearer than using one `print` statement per line or a large tuple of items to format.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.