Python:函数print()中的语法无效

lhc*_*eva 2 python printing syntax

我使用的是Python 2.7.当我尝试将简单字符串打印到文件时,出现以下错误:

语法错误:无效的元组

检测元组时出现语法错误

最小的例子:

fly = open('workfile', 'w')
print('a', file=fly)
Run Code Online (Sandbox Code Playgroud)

通过fly.write('a')工作写到同一个文件就好了.

Len*_*bro 8

您正在使用Python 2中的Python 3语法.

在Python 2中,它是这样的:

print >> fly, 'a'
Run Code Online (Sandbox Code Playgroud)

但是,更好的想法是这样做:

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

如果您使用的是Python 2.6或2.7,那将启用Python 3语法.

另见:http://docs.python.org/2/library/functions.html#print

  • @lhcgeneva:阅读刚刚链接到的链接中的注释. (2认同)