列印語句與列印功能

在 Python 2 中, print 是一個宣告:

Python 2.x <= 2.7

print "Hello World"
print                         # print a newline
print "No newline",           # add trailing comma to remove newline 
print >>sys.stderr, "Error"   # print to stderr
print("hello")                # print "hello", since ("hello") == "hello"
print()                       # print an empty tuple "()"
print 1, 2, 3                 # print space-separated arguments: "1 2 3"
print(1, 2, 3)                # print tuple "(1, 2, 3)"

在 Python 3 中, print() 是一個函式,帶有常用的關鍵字引數:

Python 3.x >= 3.0

print "Hello World"              # SyntaxError
print("Hello World")
print()                          # print a newline (must use parentheses)
print("No newline", end="")      # end specifies what to append (defaults to newline)
print("Error", file=sys.stderr)  # file specifies the output buffer
print("Comma", "separated", "output", sep=",")  # sep specifies the separator
print("A", "B", "C", sep="")     # null string for sep: prints as ABC
print("Flush this", flush=True)  # flush the output buffer, added in Python 3.3
print(1, 2, 3)                   # print space-separated arguments: "1 2 3"
print((1, 2, 3))                 # print tuple "(1, 2, 3)"

列印功能具有以下引數:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

sep 是將傳遞給列印的物件分開的東西。例如:

print('foo', 'bar', sep='~') # out: foo~bar
print('foo', 'bar', sep='.') # out: foo.bar

end 是 print 語句的結尾。例如:

print('foo', 'bar', end='!') # out: foo bar!

在非換行結束列印語句後再次列印列印到同一行:

print('foo', end='~')
print('bar')
# out: foo~bar

注意: 為了將來的相容性, print 函式也可以在 Python 2.6 之後使用; 但是除非禁用了 print 語句的解析,否則不能使用它

from __future__ import print_function

此函式與 Python 3 的格式完全相同,只是它缺少 flush 引數。

有關基本原理,請參閱 PEP 3105