【问题标题】:Does Python 2.x always return a string for print statements?Python 2.x 是否总是为打印语句返回一个字符串?
【发布时间】:2021-02-27 17:04:51
【问题描述】:

我在 Python 3.8 和 2.7 中都搞砸了,发现 Python 3 中的 print 函数不允许在 print 中使用前导零。见下文:

    >>> 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

我想这是因为 Python 3.x 即使在打印时也会区分数据类型,这就是以下工作的原因:

>>> print('01')
01

我明确要求打印一个字符串。尽管在 Python 2.7 中,以下语句没有错误:

>>> print '01'
01

它只是返回我问的内容。是不是意味着 Python 2.x 总是将打印值转换为字符串?

【问题讨论】:

  • 除了第一种情况外,您似乎在值周围加上引号......

标签: python types printf python-2.x


【解决方案1】:

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

>>> x=print 'hi'
  File "<stdin>", line 1
    x=print 'hi'
          ^
SyntaxError: invalid syntax

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

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

>>> x=print(1)
1
>>> x
>>> type(x)
<type 'NoneType'>

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

>>> 010
8

这个语法在 Python 3 中是非法的,所以你得到SyntaxError: invalid token。这发生在print 语句看到发生了什么之前,因此它与print 无关。

如果你想write a number in octal in Python3,正确的语法是0o...,如:

>>> 0o10
8

【讨论】:

  • 谢谢!您可能已经注意到对基本概念缺乏理解,我是新手。所以这真的很有帮助。
  • @FlavioHF 我建议你不要在过时的 Python 版本上使用cut your teeth,如果你能提供帮助的话 :)
猜你喜欢
  • 2020-04-01
  • 2013-07-13
  • 2015-11-14
  • 2015-12-16
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多