Name
The print Statement
Synopsis
print [value
[,value
]* [,]] print >>fileobj
[,value
[,value
]* [,]]
Displays the printable representation of values on stdout stream (the
current setting of sys.stdout
). Adds spaces
between values. Trailing comma suppresses linefeed normally added at
end of list. Because print
simply calls the
write
method of the object currently referenced by
sys.stdout
, the following is equivalent to
print
X
:
import sys sys.stdout.write(str(X) + '\n')
To redirect print
text to files or class objects,
reassign sys.stdout
to any object with a
write
method:
sys.stdout = open('log', 'a') # any object with a write( ) print "Warning-bad spam!" # goes to the object's write( )
Extended print form
As of Python 2.0, the print
statement may also
name an open output file-like object to be the target of the printed
text (instead of sys.stdout
):
fileobj = open('log', 'a') print >> fileobj, "Warning-bad spam!"
If the file object is None
,
sys.stdout
is used. Because
sys.stdout
can be reassigned, the
>>
form is not strictly needed; however, it
can often avoid both explicit write
method calls
and saving and restoring the original sys.stdout
value around a redirected print
.
Get Python Pocket Reference, Second Edition 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.