4.9. The print Statement
A print statement is denoted by the keyword print followed by zero or more expressions separated by commas. print is a handy, simple way to output values in text form, mostly for debugging purposes. print outputs each expression x as a string that's just like the result of calling str(x) (covered in str on page 157). print implicitly outputs a space between expressions, and implicitly outputs \n after the last expression, unless the last expression is followed by a trailing comma (,). Here are some examples of print statements:
letter = 'c' print "give me a", letter, "..." # prints: give me a c... answer = 42 print "the answer is:", answer # prints: the answer is: 42
The destination of print's output is the file or file-like object that is the value of the stdout attribute of the sys module (covered in "The sys Module" on page 168). If you want to direct the output from a certain print statement to a specific file object f (which must be open for writing), you can use the special syntax:
print >>f, rest of print statement
(if f is None, the destination is sys.stdout, just as it would be without the >>f ). You can also use the write or writelines methods of file objects, as covered in "Attributes and Methods of File Objects" on page 218. However, print is very simple to use, and simplicity is important in the common case where all you need are the simple output strategies that print suppliesin particular, this is often the case for the kind of simple output statements you may temporarily add to a program for debugging purposes. "The print Statement" on page 256 has more advice and examples concerning the use of print.