预计阅读本页时间:-
The Python 3.0 print Function
Strictly speaking, printing is not a separate statement form in 3.0. Instead, it is simply an instance of the expression statement we studied in the preceding section.
The print built-in function is normally called on a line of its own, because it doesn’t return any value we care about (technically, it returns None). Because it is a normal function, though, printing in 3.0 uses standard function-call syntax, rather than a special statement form. Because it provides special operation modes with keyword arguments, this form is both more general and supports future enhancements better.
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
By comparison, Python 2.6 print statements have somewhat ad-hoc syntax to support extensions such as end-of-line suppression and target files. Further, the 2.6 statement does not support separator specification at all; in 2.6, you wind up building strings ahead of time more often than you do in 3.0.
Call format
Syntactically, calls to the 3.0 print function have the following form:
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
In this formal notation, items in square brackets are optional and may be omitted in a given call, and values after = give argument defaults. In English, this built-in function prints the textual representation of one or more objects separated by the string sep and followed by the string end to the stream file.
The sep, end, and file parts, if present, must be given as keyword arguments—that is, you must use a special “name=value” syntax to pass the arguments by name instead of position. Keyword arguments are covered in depth in Chapter 18, but they’re straightforward to use. The keyword arguments sent to this call may appear in any left-to-right order following the objects to be printed, and they control the print operation:
- sep is a string inserted between each object’s text, which defaults to a single space if not passed; passing an empty string suppresses separators altogether.
- end is a string added at the end of the printed text, which defaults to a \n newline character if not passed. Passing an empty string avoids dropping down to the next output line at the end of the printed text—the next print will keep adding to the end of the current output line.
- file specifies the file, standard stream, or other file-like object to which the text will be sent; it defaults to the sys.stdout standard output stream if not passed. Any object with a file-like write(string) method may be passed, but real files should be already opened for output.
The textual representation of each object to be printed is obtained by passing the object to the str built-in call; as we’ve seen, this built-in returns a “user friendly” display string for any object.[29] With no arguments at all, the print function simply prints a newline character to the standard output stream, which usually displays a blank line.
The 3.0 print function in action
Printing in 3.0 is probably simpler than some of its details may imply. To illustrate, let’s run some quick examples. The following prints a variety of object types to the default standard output stream, with the default separator and end-of-line formatting added (these are the defaults because they are the most common use case):
C:\misc> c:\python30\python
>>>
>>> print() # Display a blank line
>>> x = 'spam'
>>> y = 99
>>> z = ['eggs']
>>>
>>> print(x, y, z) # Print 3 objects per defaults
spam 99 ['eggs']
There’s no need to convert objects to strings here, as would be required for file write methods. By default, print calls add a space between the objects printed. To suppress this, send an empty string to the sep keyword argument, or send an alternative separator of your choosing:
>>> print(x, y, z, sep='') # Suppress separator
spam99['eggs']
>>>
>>> print(x, y, z, sep=', ') # Custom separator
spam, 99, ['eggs']
Also by default, print adds an end-of-line character to terminate the output line. You can suppress this and avoid the line break altogether by passing an empty string to the end keyword argument, or you can pass a different terminator of your own (include a \n character to break the line manually):
>>> print(x, y, z, end='') # Suppress line break
spam 99 ['eggs']>>>
>>>
>>> print(x, y, z, end=''); print(x, y, z) # Two prints, same output line
spam 99 ['eggs']spam 99 ['eggs']
>>> print(x, y, z, end='...\n') # Custom line end
spam 99 ['eggs']...
>>>
You can also combine keyword arguments to specify both separators and end-of-line strings—they may appear in any order but must appear after all the objects being printed:
>>> print(x, y, z, sep='...', end='!\n') # Multiple keywords
spam...99...['eggs']!
>>> print(x, y, z, end='!\n', sep='...') # Order doesn't matter
spam...99...['eggs']!
Here is how the file keyword argument is used—it directs the printed text to an open output file or other compatible object for the duration of the single print (this is really a form of stream redirection, a topic we will revisit later in this section):
>>> print(x, y, z, sep='...', file=open('data.txt', 'w')) # Print to a file
>>> print(x, y, z) # Back to stdout
spam 99 ['eggs']
>>> print(open('data.txt').read()) # Display file text
spam...99...['eggs']
Finally, keep in mind that the separator and end-of-line options provided by print operations are just conveniences. If you need to display more specific formatting, don’t print this way, Instead, build up a more complex string ahead of time or within the print itself using the string tools we met in Chapter 7, and print the string all at once:
>>> text = '%s: %-.4f, %05d' % ('Result', 3.14159, 42)
>>> print(text)
Result: 3.1416, 00042
>>> print('%s: %-.4f, %05d' % ('Result', 3.14159, 42))
Result: 3.1416, 00042
As we’ll see in the next section, almost everything we’ve just seen about the 3.0 print function also applies directly to 2.6 print statements—which makes sense, given that the function was intended to both emulate and improve upon 2.6 printing support.