Python中print和prints有什么区别?

3

Python中的打印有哪些不同之处:

print 'smth'
print('smth')

没有实际区别,第一个只是一种语法糖。 - gravetii
3
不,第二种方法只有在Python 2中print是语句而不是函数的情况下才能巧合地起作用。而第一种方法才是正确的用法,它不是语法糖。 - Wooble
3个回答

7

print 在 Python 3 中被改为函数形式(而以前是语句),因此你的第一行代码是 Python 2 风格的,后者是 Python 3 风格。

更具体地说,在 Python 2 中,使用 () 打印意味着打印一个元组:

In [1414]: print 'hello', 'kitty'
hello kitty

In [1415]: print ('hello', 'kitty')
('hello', 'kitty')

In [1416]: print ('hello') #equals: print 'hello', 
                           #since "()" doesn't make a tuple, the commas "," do
hello

在Python3中,没有使用()的print语句会导致SyntaxError错误。
In [1]: print ('hello', 'kitty')
hello kitty

In [2]: print 'hello', 'kitty'
  File "<ipython-input-2-d771e9da61eb>", line 1
    print 'hello', 'kitty'
                ^
SyntaxError: invalid syntax

3
在Python2中,print('smth')是有效的。因为('smth')等同于写成'smth' - Loïc Faure-Lacroix
1
@LoïcFaure-Lacroix 不是这样的。 ('smth') 仍然是字符串,但 ('smth',) 是元组。 - J0HN
@LoïcFaure-Lacroix 或许你看到了我在更新后的评论。竞态条件 :) - J0HN
为了更加混淆,() 不是生成元组的关键,逗号才是。但是 print 语句的语法使逗号有不同的作用,而 () 又会让它们重新生成元组。 - Wooble
@Wooble 是的,但你不会想要 ((3 + 4) + 4),作为 tuple(tuple(3 + 4) + 4),除非你能提出一种新的括号类型,而这种类型还没有被使用过。 - Loïc Faure-Lacroix
显示剩余2条评论

4
在Python 3中,print是一个函数。
>>> print('a','b','c')
a b c

在Python 2中,print是一个关键字,其功能较为有限:
>>> print 'a','b','c' 
a b c

虽然在 Python 2 中 print() 可以使用,但它并不是你想象中的那样。如果有多个元素,它会打印出一个元组:
>>> print('a','b','c')
('a', 'b', 'c')

在仅有一个元素的括号表达式的情况下,括号会被去除:
>>> print((((('hello')))))
hello

但这只是Python表达式解析器的操作,而不是print函数的操作:

>>> ((((('hello')))))
'hello'

如果是元组,则打印元组:
>>> print((((('hello',)))))
('hello',)

您可以通过导入来在Python 2中获得Python 3的打印函数:

>>> print('a','b','c')
('a', 'b', 'c')
>>> from __future__ import print_function
>>> print('a','b','c')
a b c

PEP 3105讨论了这个变化。


0

在Python 2和3的print中您可以使用括号,但在Python 3中必须使用它们。

Python 2:

print "Hello"

或者:

print("Hello")

而在Python 3中:

print "Hello"

让你得到这个:

  File "<stdin>", line 1
    print "Hello"
                ^
SyntaxError: Missing parentheses in call to 'print'

所以你需要做:

print("Hello")  

事实是,在Python 2中,print是一个语句,但在Python 3中,它是一个函数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接