打印语句与打印功能

在 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