原创关于python3和python2中print的理解

Posted runpython

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原创关于python3和python2中print的理解相关的知识,希望对你有一定的参考价值。

在python3中的print是一个内置的函数(对象),所以所有的输出要像这样print()
而python2中的print只是一个声明,它的输出是这样 print prt或print "prt"
参考官方说明:
#python2.x

% pydoc2.6 print

The ``print`` statement
***********************

print_stmt ::= "print" ([expression ("," expression)* [","]]
| ">>" expression [("," expression)+ [","]])

``print`` evaluates each expression in turn and writes the resulting
object to standard output (see below). If an object is not a string,
it is first converted to a string using the rules for string
conversions. The (resulting or original) string is then written. A
space is written before each object is (converted and) written, unless
the output system believes it is positioned at the beginning of a
line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is a whitespace character except ``‘ ‘``, or (3) when the last
write operation on standard output was not a ``print`` statement. (In
some cases it may be functional to write an empty string to standard
output for this reason.)

python3.x

% pydoc3.1 print

Help on built-in function print in module builtins:

print(...)
print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.

在此,我们再加以论证。
在python2中,
我们执行type(print),将返回如下的错误:
>>> type(print)
  File "<stdin>", line 1
    type(print)
             ^
SyntaxError: invalid syntax
在python3中,
我们执行type(print),将返回:
>>> type(print)
<class ‘builtin_function_or_method‘>
>>>
返回了信息意思就是“类:内置函数或对象”

那我们在python2中能不能像python3中,像print()这样使用?
答案是可以的。
在python2中,我们把 from __future__ import print_function 放在脚本顶部(就是代码的第一行)位置。
那么,该print语句将被替换为print()函数。
在python2中我们测试下:
>>> from __future__ import print_function
>>> print "a"
  File "<stdin>", line 1
    print "a"
            ^
SyntaxError: invalid syntax
>>> type(print)
<type ‘builtin_function_or_method‘>
>>>
理论是正确的。

























































以上是关于原创关于python3和python2中print的理解的主要内容,如果未能解决你的问题,请参考以下文章

Python2和Python3中print的不同点

python3和Python2的区别

Python2 和 Python3 区别汇总

python2和python3的区别

python3和Python2的区别(被坑太久了)

python2与python3之间的主要区别