Does Python 2.x always return a string for print statements?

1 python printf types python-2.x

I was messing around with both Python 3.8 and 2.7 and found out that the print function in Python 3 doesn't allow leading zeros in print. See below:

    >>> print(01)
  File "<stdin>", line 1
    print(01)
           ^
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
Run Code Online (Sandbox Code Playgroud)

I suppose this happens because Python 3.x differentiate data types even when printing, this is why the following works:

>>> print('01')
01
Run Code Online (Sandbox Code Playgroud)

I explicitly asked to print a string. Though in Python 2.7 there is no error with the following statement:

>>> print '01'
01
Run Code Online (Sandbox Code Playgroud)

It just returns what I asked. Does it mean that Python 2.x always converts print values into strings?

koj*_*iro 5

在原始 python 2 中,print是一个语句,根本不是return一个值。

>>> x=print 'hi'
  File "<stdin>", line 1
    x=print 'hi'
          ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

如果您在 python 2.7 中使用未来兼容的打印函数,那么它的行为与 Python 3 完全一样。

在 Python 3 中print,一个函数总是返回None。它打印到一个文件(通常是标准输出),但函数返回的值是None.

>>> x=print(1)
1
>>> x
>>> type(x)
<type 'NoneType'>
Run Code Online (Sandbox Code Playgroud)

至于1vs 01,在 Python 2 中,带有前导零的数字是八进制:

>>> 010
8
Run Code Online (Sandbox Code Playgroud)

这种语法在 Python 3 中是非法的,所以你得到SyntaxError: invalid token. 这发生在print语句看到正在发生的事情之前,所以它与print.

如果你想在 Python3 中用八进制写一个数字,正确的语法0o...如下:

>>> 0o10
8
Run Code Online (Sandbox Code Playgroud)