2009-05-05 94 views
232

为什么在Python 3中打印字符串时收到语法错误?使用Python 3打印语法错误

>>> print "hello World" 
    File "<stdin>", line 1 
    print "hello World" 
        ^
SyntaxError: invalid syntax 
+15

提示:对于python 2.7+中的兼容性代码,将其放入模块的开头:`from __future__ import print_function` – 2013-08-12 13:12:46

回答

314

在Python 3中,printbecame a function。这意味着,你现在需要包括括号类似下面:

print("Hello World") 
18

在Python 3.0,print是一个普通的功能,需要():

print("Hello world") 
15

它看起来像你使用Python 3,在Python 3,打印已改为一个方法,而不是的声明。试试这个:

print("hello World") 
16

在Python 3,这是print("something"),不print "something"

27

因为在Python 3中,print statement已被替换为print() function,其中用关键字参数替换了大部分旧的print语句的特殊语法。所以,你必须把它写成

print("Hello World") 

但是,如果你写这个程序中,有一种用Python 2.x的尝试运行,他们会得到一个错误。为了避免这种情况,这是一个很好的做法,导入打印功能

from __future__ import print_function 

现在你的代码工作在两个2.X & 3.X

看看下面的例子也让熟悉print()函数。

Old: print "The answer is", 2*2 
New: print("The answer is", 2*2) 

Old: print x,   # Trailing comma suppresses newline 
New: print(x, end=" ") # Appends a space instead of a newline 

Old: print    # Prints a newline 
New: print()   # You must call the function! 

Old: print >>sys.stderr, "fatal error" 
New: print("fatal error", file=sys.stderr) 

Old: print (x, y)  # prints repr((x, y)) 
New: print((x, y))  # Not the same as print(x, y)! 

来源:What’s New In Python 3.0?

5

在Python 2.X printkeyword,而在Python 3.X print成为一个功能,所以做正确的做法是print(something)

你可以通过执行获得的关键字列表每个版本如下:

>>> import keyword 
>>> keyword.kwlist 
7

你必须使用支架与打印print("Hello World")

8

在Python 3中,您必须执行print('some code')。这是因为在Python 3中它已经成为一种功能。如果您必须,您可以使用Python 2代码并使用2to3将其转换为Python 3代码 - 这是一个内置于Python中的优秀程序。欲了解更多信息,请参阅Python 2to3 - Convert your Python 2 to Python 3 automatically!