Python 2.7中print()函数的错误

5

使用Python的print()函数中的sepfile等参数时,我遇到了奇怪的错误。 我尝试通过谷歌搜索、在Stack Overflow上查找并阅读Python文档,但都没有找到解决方法。 我附上了一个简单的代码片段,非常感谢任何帮助。

# python
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("blah"*10, sep=" | ")
  File "<stdin>", line 1
    print("blah"*10, sep=" | ")
                        ^
SyntaxError: invalid syntax
3个回答

11

尝试:

from __future__ import print_function

第一个


谢谢你。它确实解决了问题。那么为什么Python文档(请参见我的更新帖子)规定不同呢?另外,您知道在哪里可以找到有关原生使用print()函数的相关文档吗? - Mr.
2
@MrRoth:请阅读您链接中的注释 ;) - phant0m

6
在2.x系列中,print是一个语句,而在3.x中它是一个函数。如果你想在2.6+中将print作为一个函数使用,你需要在第一个导入语句中使用from __future__ import print_function。请注意,这可能会导致代码出现问题。

0
打印函数是专门针对Python 3的。 在这里你有两个解决方案:
from __future__ import print_function

所以,您可以根据cdarke的规定使用它。

或者,您可以像在旧版Python中一样使用print作为简单语句(print "Hello World")。


使用旧的 print 语句的问题在于分隔符无法更改,而当前的 print() 函数可以更改。 - cdarke

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接