python中打印的括号

Tri*_*ger 5 python printing

我在python中有这行代码

print 'hello world'
Run Code Online (Sandbox Code Playgroud)

反对

print ('hello world')
Run Code Online (Sandbox Code Playgroud)

谁能告诉我两者之间的区别?

我在一个简单的代码中使用它

var = 3
if var > 2: 
    print 'hello'
Run Code Online (Sandbox Code Playgroud)

它无法严格检查var的所有值.但是,如果我将代码定义为

var = 3
if var > 2: 
    print ('hello')
Run Code Online (Sandbox Code Playgroud)

有用!

pok*_*oke 14

对于Python 2,它没有任何区别.在那里,print是一个声明,'hello'并且('hello')是它的论点.后者被简化为正义'hello',因此它是相同的.

在Python 3中,删除了print语句以支持打印功能.使用大括号调用函数,因此实际需要它们.在这种情况下,这print 'hello'是一个语法错误,而print('hello')调用函数'hello'作为其第一个参数.

您可以通过显式导入将打印功能向后移植到Python 2.为此,添加以下内容作为模块的第一个导入:

from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)

然后,您将从Python 2中的Python 3获得相同的行为,并且再次需要括号.


Ash*_*ary 9

你应该阅读python 3.0中的新功能:

print语句已被替换为一个print()函数,其中包含用于替换旧打印语句(PEP 3105)的大部分特殊语法的关键字参数.

向后兼容性:

本PEP中提出的更改将使今天的大多数打印报表无效.只有那些偶然在其所有参数周围具有括号的那些将继续在3.0版本中有效的Python语法,其中,只有打印单个括号值的那些将继续执行相同的操作.例如,在2.x中:

>>> print ("Hello", "world")  # without import
('Hello', 'world')

>>> from __future__ import print_function  

>>> print ("Hello", "world")       # after import 
Hello world
Run Code Online (Sandbox Code Playgroud)