2
votes

As the title says, how to replace all: print "string", in Python2 with: print("string"), for Python3?

I really wish they made this one function backward compatible. Officially the 2to3.py script is recommended, but it always seems like its just the print statements that i need to replace in Py2 script examples, say running in a notebook or Jupyter lab (which makes the 2to3.py less appealing - unless they implemented a converter!)

.

@Bazingaa, @Wiktor Stribiżew, @jpp: Not duplicate, i.e. not forwards compatiblity. I.E., I'm not asking how to use Python3 syntax in Python2, which would be forwards compatiblity, but the opposite which is reverse compatibility.

@jpp I'm shocked at your level of reading comprehension, even after adding clarification. I included those 'possible duplicates' originally in my answer below and explained the difference (which you must have also failed to read before adding your tags and comment), which do not 'give me what I'm looking for'. Appreciate the 'peril' caution, but again you missed the whole point, that I'm using Python 3.. trying to change the syntax from Python 2 in old tutorial scripts. Don't know how you could read that incorrectly twice. My solution below is valid, one I've looked for for years, and will undoubtedly help others who land here.

2
Not duplicate, i.e. not forwards compatible.alchemy
Added some duplicates that give you the regex for what you're looking for. Aside, officially Python 2 will soon no longer be supported. Use Python 2 at your own peril.jpp
instead of using regex, run 2to3 from cli (follow its help)Leon

2 Answers

3
votes

This and this show solutions for Vim, but this one works for Windows and print variable statements.

Works well in old Python2 example scripts. Otherwise use 2to3.py for additional conversions.

Try it out on regexr.com (doesn't work in NP++ for some reason):

find:    (?<=print)( ')(.*)(')
replace: ('$2')

for variables:

(?<=print)( )(.*)(\n)
('$2')\n

for label and variable:

(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
1
votes

They did make that function backwards compatible. Import it from future at the start of the file.

from __future__ import print_function

Well, forwards compatible. For now you're just with a find and replace in your ide.