为什么在Python 3中打印字符串时会收到语法错误?
>>> print "hello World"
File "<stdin>", line 1
print "hello World"
^
SyntaxError: invalid syntax
为什么在Python 3中打印字符串时会收到语法错误?
>>> print "hello World"
File "<stdin>", line 1
print "hello World"
^
SyntaxError: invalid syntax
因为在Python 3中,print语句
已被替换为print()函数
,使用关键字参数替换了旧的print语句的大部分特殊语法。因此,您需要将其编写为:
print("Hello World")
但是,如果您在程序中编写此代码,并且有人试图在使用Python 2.x的环境中运行它,将会出现错误。为了避免这种情况,最好导入print函数:
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)!
from __future__ import print_function
。此代码的作用是将Python 3.x中的print函数引入到当前模块中,以便在Python 2.7+版本中使用。注意,此操作不会改变原有功能,只是提高了兼容性。 - Yauhen Yakimovich