[英]What is the difference between prints in python
What is the difference between prints in python: python中打印的区别是什么:
print 'smth'
print('smth')
print
is made a function in python 3 (whereas before it was a statement), so your first line is python2 style, the latter is python3 style. print
在python 3中成为一个函数(而在它之前是一个语句),所以你的第一行是python2样式,后者是python3样式。
to be specific, in python2, printing with ()
intends to print a tuple: 具体来说,在python2中,打印用()
打算打印一个元组:
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
in python3, print without ()
gives a SyntaxError: 在python3中,print without ()
给出了一个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
In python 3, print is a function. 在python 3中, print是一个函数。
>>> print('a','b','c')
a b c
In Python 2, print is a keyword with more limited functionality: 在Python 2中, print是一个功能有限的关键字:
>>> print 'a','b','c'
a b c
While print()
works in Python 2, it is not doing what you may think. 虽然print()
在Python 2中有效,但它并没有按照您的想法行事。 It is printing a tuple if there is more than one element: 如果有多个元素,它会打印一个元组:
>>> print('a','b','c')
('a', 'b', 'c')
For the limited case of a one element parenthesis expression, the parenthesis are removed: 对于单元素括号表达式的有限情况,将删除括号:
>>> print((((('hello')))))
hello
But this is just the action of the Python expression parser, not the action of print: 但这只是Python表达式解析器的操作,而不是print的操作:
>>> ((((('hello')))))
'hello'
If it is a tuple, a tuple is printed: 如果它是一个元组,则会打印一个元组:
>>> print((((('hello',)))))
('hello',)
You can get the Python 3 print function in Python 2 by importing it: 您可以通过导入Python 2中的Python 3打印功能:
>>> print('a','b','c')
('a', 'b', 'c')
>>> from __future__ import print_function
>>> print('a','b','c')
a b c
You can use parenthesis in Python 2 and 3 print
, but they are a must in Python 3. 你可以在Python 2和3使用括号print
,但他们在Python 3一绝。
Python 2: Python 2:
print "Hello"
or: 要么:
print("Hello")
Whereas in Python 3: 而在Python 3中:
print "Hello"
Gets you this: 得到你:
File "<stdin>", line 1
print "Hello"
^
SyntaxError: Missing parentheses in call to 'print'
So you need to do: 所以你需要这样做:
print("Hello")
The thing is, in Python 2, print
is a statement, but in Python 3, it's a function. 问题是,在Python 2中, print
是一个语句,但在Python 3中,它是一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.