【问题标题】:Print in python 2.7在 python 2.7 中打印
【发布时间】:2016-07-08 15:27:32
【问题描述】:

我使用 Python 2.7 已经有一段时间了。 突然,我的 print 语句出现错误,看起来我现在应该使用 Python 3.x 语法。

print 'hello world'
File "<ipython-input-462-d05d0c8adf1f>", line 1
   print 'hello world'
                  ^
SyntaxError: invalid syntax

print('hello world')
hello world

我再次确认我仍在运行 2.x Python 版本:

import sys
print (sys.version)
2.7.12 |Anaconda 2.3.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]

我最近对我的 Python 环境所做的唯一更改是将 matplotlib 从 1.4 更新到 1.5,但老实说,我不能说问题是否从更新的确切时刻开始。

任何帮助将不胜感激(请让我知道我的系统上还需要哪些其他信息)

【问题讨论】:

  • 你有from __future__ import print_function吗?

标签: python python-2.7


【解决方案1】:

您是否使用print_function 未来导入?

from __future__ import print_function

该函数将新的打印语法反向移植到 Python 2 代码。如果代码库应该在 Python 2 和 3 上都可以运行,则通常使用它。

例子:

>>> print 'hello'
hello
>>> from __future__ import print_function
>>> print 'hello'
  File "<stdin>", line 1
    print 'hello'
                ^
SyntaxError: invalid syntax
>>> print('hello')
hello

更多详情请见the __future__ docs

如果您自己没有使用该导入,您可以测试该问题是仅出现在 ipython 还是常规 python,以缩小问题的根源。

【讨论】:

  • “你正在使用的库”——这只会影响库,而不是提问者,因为未来的陈述是模块本地的。
  • 您能详细说明一下吗?我从来没有在我的脚本中使用过它,所以我怀疑它一定包含在我正在使用的一些库中。这会不会有问题?只需重新启动内核即可解决问题,因此很可能我必须使用 print_function future import
  • @FLab 啊,你用的是 jupyter/ipython notebook?在最后一次启动内核后,您是否可能粘贴了一些包含过去导入的测试代码?您是否在笔记本中使用了一些“魔术”导入(以 % 符号开头的)?
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 2013-08-29
  • 2016-12-03
  • 1970-01-01
  • 2012-03-08
  • 2018-04-24
  • 2011-12-14
  • 1970-01-01
相关资源
最近更新 更多