例
在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 。