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

paul23 picture paul23 · Mar 6, 2015 · Viewed 20k times · Source

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).

Answer

Martijn Pieters picture Martijn Pieters · Mar 6, 2015

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.