Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between prints in python

Tags:

python

What is the difference between prints in python:

print 'smth'
print('smth')
like image 837
Edd Avatar asked May 23 '26 13:05

Edd


2 Answers

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.

to be specific, in python2, printing with () intends to print a tuple:

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:

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
like image 84
zhangxaochen Avatar answered May 26 '26 04:05

zhangxaochen


In python 3, print is a function.

>>> print('a','b','c')
a b c

In Python 2, print is a keyword with more limited functionality:

>>> print 'a','b','c' 
a b c

While print() works in Python 2, it is not doing what you may think. 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:

>>> ((((('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:

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

PEP 3105 discusses the change.

like image 41
dawg Avatar answered May 26 '26 03:05

dawg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!