为什么在Python 3中打印字符串时收到语法错误?使用Python 3打印语法错误
>>> print "hello World"
File "<stdin>", line 1
print "hello World"
^
SyntaxError: invalid syntax
为什么在Python 3中打印字符串时收到语法错误?使用Python 3打印语法错误
>>> print "hello World"
File "<stdin>", line 1
print "hello World"
^
SyntaxError: invalid syntax
在Python 3中,print
became a function。这意味着,你现在需要包括括号类似下面:
print("Hello World")
它看起来像你使用Python 3.0,其中,而不是一份声明中print has turned into a callable function。
print('Hello world!')
在Python 3.0,print
是一个普通的功能,需要():
print("Hello world")
它看起来像你使用Python 3,在Python 3,打印已改为一个方法,而不是的声明。试试这个:
print("hello World")
在Python 3,这是print("something")
,不print "something"
。
因为在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)!
在Python 2.X print
是keyword,而在Python 3.X print
成为一个功能,所以做正确的做法是print(something)
。
你可以通过执行获得的关键字列表每个版本如下:
>>> import keyword
>>> keyword.kwlist
你必须使用支架与打印print("Hello World")
2to3的是一个Python程序,读取的Python 2.x的源代码和应用一系列固定器将它转变成有效的Python 3.x的代码
进一步的信息可以在这里找到:
Python Documentation: Automated Python 2 to 3 code translation
在Python 3中,您必须执行print('some code')
。这是因为在Python 3中它已经成为一种功能。如果您必须,您可以使用Python 2代码并使用2to3
将其转换为Python 3代码 - 这是一个内置于Python中的优秀程序。欲了解更多信息,请参阅Python 2to3 - Convert your Python 2 to Python 3 automatically!。
提示:对于python 2.7+中的兼容性代码,将其放入模块的开头:`from __future__ import print_function` – 2013-08-12 13:12:46