Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python 3.x make print work like in Python 2 (as statement)

Tags:

I wonder if the print function can be made work (without changing the syntax all over the place) like in Python 2 and earlier.

So I have the statement like:

print "Hello, World!" 

And I like that syntax to work in Python 3. I've tried importing the library six, but that didn't do the trick (still a syntax error).

like image 760
paul23 Avatar asked Mar 06 '15 10:03

paul23


People also ask

Is print a statement in Python 2?

However, if we have multiple objects inside the parantheses, we will create a tuple, since print is a “statement” in Python 2, not a function call.

Does code Python 2 work with Python 3?

Python 2.6 includes many capabilities that make it easier to write code that works on both 2.6 and 3. As a result, you can program in Python 2 but using certain Python 3 extensions... and the resulting code works on both.

What is the difference between print in Python 2 and 3?

In Python 2, print is a statement that does not need a parenthesis. In Python 3, print is a function and the values need to be written in parenthesis.

What is the difference between Python 2x and 3x?

In Python 3, print is considered to be a function and not a statement. In Python 2, strings are stored as ASCII by default. In Python 3, strings are stored as UNICODE by default. On the division of two integers, we get an integral value in Python 2.


1 Answers

No, you cannot. The print statement is gone in Python 3; the compiler doesn't support it anymore.

You can make print() work like a function in Python 2; put this at the top of every module that uses print:

from __future__ import print_function 

This will remove support for the print statement in Python 2 just like it is gone in Python 3, and you can use the print() function that ships with Python 2.

six can only help bridge code written with both Python 2 and 3 in mind; that includes replacing print statements with print() functions first.

You probably want to read the Porting Python 2 Code to Python 3 howto; it'll tell you about more such from __future__ imports as well, as well as introduce tools such as Modernize and Futurize that can help automate fixing Python 2 code to work on both Python 2 and 3.

like image 61
Martijn Pieters Avatar answered Sep 20 '22 13:09

Martijn Pieters