为什么在 Python 2.7 中打印括号是自愿的? [英] Why is parenthesis in print voluntary in Python 2.7?
问题描述
在 Python 2.7 中,以下两者都将执行相同的操作
In Python 2.7 both the following will do the same
print("Hello, World!") # Prints "Hello, World!"
print "Hello, World!" # Prints "Hello, World!"
但是以下不会
print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")
print "Hello,", "World!" # Prints the words "Hello, World!"
在 Python 3.x 中,print
上的括号是强制性的,本质上使其成为一个函数,但在 2.7 中两者都会产生不同的结果.关于 Python 2.7 中的 print
,我还应该了解什么?
In Python 3.x parenthesis on print
is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print
in Python 2.7?
推荐答案
在 Python 2.x 中 print
实际上是一个特殊的语句而不是函数*.
In Python 2.x print
is actually a special statement and not a function*.
这也是它不能像这样使用的原因:lambda x: print x
This is also why it can't be used like: lambda x: print x
请注意,(expr)
不会创建元组(它会生成 expr
),但是 ,
会.这可能会导致 Python 2.7 中 print (x)
和 print (x, y)
之间的混淆
Note that (expr)
does not create a Tuple (it results in expr
), but ,
does. This likely results in the confusion between print (x)
and print (x, y)
in Python 2.7
(1) # 1 -- no tuple Mister!
(1,) # (1,)
(1,2) # (1, 2)
1,2 # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]
然而,由于 print
是 Python 2.x 中的一个特殊语法语句/语法结构,那么在没有括号的情况下,它会处理 ,
以一种特殊的方式 - 并且不会创建一个元组.print
语句的这种特殊处理使其能够在尾随 ,
与否的情况下执行不同的操作.
However, since print
is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,
's in a special manner - and does not create a Tuple. This special treatment of the print
statement enables it to act differently if there is a trailing ,
or not.
快乐编码.
*Python 2 中的此 print
行为可以更改为 Python 3 的行为:
*This print
behavior in Python 2 can be changed to that of Python 3:
from __future__ import print_function
这篇关于为什么在 Python 2.7 中打印括号是自愿的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!