预计阅读本页时间:-
The Python 2.6 print Statement
As mentioned earlier, printing in Python 2.6 uses a statement with unique and specific syntax, rather than a built-in function. In practice, though, 2.6 printing is mostly a variation on a theme; with the exception of separator strings (which are supported in 3.0 but not 2.6), everything we can do with the 3.0 print function has a direct translation to the 2.6 print statement.
Statement forms
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Table 11-5 lists the print statement’s forms in Python 2.6 and gives their Python 3.0 print function equivalents for reference. Notice that the comma is significant in print statements—it separates objects to be printed, and a trailing comma suppresses the end-of-line character normally added at the end of the printed text (not to be confused with tuple syntax!). The >> syntax, normally used as a bitwise right-shift operation, is used here as well, to specify a target output stream other than the sys.stdout default.
Table 11-5. Python 2.6 print statement forms
Python 2.6 statement
Python 3.0 equivalent
Interpretation
print x, y
print(x, y)
Print objects’ textual forms to sys.stdout; add a space between the items and an end-of-line at the end
print x, y,
print(x, y, end='')
Same, but don’t add end-of-line at end of text
print >> afile, x, y
print(x, y, file=afile)
Send text to myfile.write, not to sys.stdout.write
The 2.6 print statement in action
Although the 2.6 print statement has more unique syntax than the 3.0 function, it’s similarly easy to use. Let’s turn to some basic examples again. By default, the 2.6 print statement adds a space between the items separated by commas and adds a line break at the end of the current output line:
C:\misc> c:\python26\python
>>>
>>> x = 'a'
>>> y = 'b'
>>> print x, y
a b
This formatting is just a default; you can choose to use it or not. To suppress the line break so you can add more text to the current line later, end your print statement with a comma, as shown in the second line of Table 11-5 (the following is two statements on one line, separated by a semicolon):
>>> print x, y,; print x, y
a b a b
To suppress the space between items, again, don’t print this way. Instead, build up an output string using the string concatenation and formatting tools covered in Chapter 7, and print the string all at once:
>>> print x + y
ab
>>> print '%s...%s' % (x, y)
a...b
As you can see, apart from their special syntax for usage modes, 2.6 print statements are roughly as simple to use as 3.0’s function. The next section uncovers the way that files are specified in 2.6 prints.