使用文件的 python print 语句中的无效语法错误

Vik*_*kyB 7 python

print('Group output sizes: |A| = {}, |B| = {}'.format(len(A),len(B)),    file=stderr)
                                                                             ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮忙看看这个错误是什么吗?我最初认为这是因为打印语法,但我认为不是。

请帮忙。

小智 5

看起来好像您正在尝试print在 Python 2.x 中使用 Python 3.x 的函数。为此,您需要首先print_function从以下位置导入__future__

将以下行放在源文件的最顶部、任何注释和/或文档字符串之后:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

下面是一个演示:

>>> # Python 2.x interpreter session
...
>>> print('a', 'b', sep=',')
  File "<stdin>", line 1
    print('a', 'b', sep=',')
                       ^
SyntaxError: invalid syntax
>>>
Run Code Online (Sandbox Code Playgroud)


>>> # Another Python 2.x interpreter session
...
>>> from __future__ import print_function
>>> print('a', 'b', sep=',')
a,b
>>>
Run Code Online (Sandbox Code Playgroud)


NPE*_*NPE 0

看起来您正在尝试print在 Python 2 中使用 Python 3 语法。

要么使用 Python 3 解释器,要么重写print如下:

print >>sys.stderr, 'Group output sizes: |A| = {}, |B| = {}'.format(len(A),len(B))
Run Code Online (Sandbox Code Playgroud)