在python中打印周围的括号 [英] brackets around print in python
问题描述
我在python中有这行代码
I have this line of code in python
print 'hello world'
反对
print ('hello world')
谁能告诉我两者的区别?
can someone tell me the difference between the two?
我在一个简单的代码中使用了它
I used it in a a simple code
var = 3
if var > 2:
print 'hello'
它无法严格检查 var 的所有值.但是如果我将代码定义为
it fails for checking strictly for all values for var. But if I define the code as
var = 3
if var > 2:
print ('hello')
它有效!
推荐答案
对于 Python 2,它没有区别.在那里,print
是一个语句,'hello'
和 ('hello')
是它的参数.后者被简化为 'hello'
,因此它是相同的.
For Python 2, it makes no difference. There, print
is a statement and 'hello'
and ('hello')
are its argument. The latter gets simplified to just 'hello'
and as such it’s identical.
在 Python 3 中,删除了打印语句以支持打印功能.使用大括号调用函数,因此实际上需要它们.在这种情况下, print 'hello'
是一个语法错误,而 print('hello')
使用 'hello'
作为调用函数它的第一个参数.
In Python 3, the print statement was removed in favor of a print function. Functions are invoked using braces, so they are actually needed. In that case, the print 'hello'
is a syntax error, while print('hello')
invokes the function with 'hello'
as its first argument.
您可以通过显式导入将打印函数向后移植到 Python 2.为此,将以下内容添加为模块的第一次导入:
You can backport the print function to Python 2, by importing it explicitly. To do that add the following as the first import of your module:
from __future__ import print_function
然后您将在 Python 2 中获得与 Python 3 相同的行为,同样需要括号.
Then you will get the same behaviour from Python 3 in Python 2, and again the parentheses are required.
这篇关于在python中打印周围的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!