Yethrosh Yethrosh - 1 month ago 12
Python Question

String replacements using re.sub in python

While learning Python regex, I want to replace all Python 2x like print functions to Python 3x like using

re.sub
:

import re

with open("py2.py", "r") as f:
matter = f.read()
mtr = re.sub(r"print\s+\"(.+)\"+",r"print(", matter)
with open("pr.py", "w") as f:
final = f.write(mtr)


Matter of py2.py is:

print "Anything goes here"
print "Anything"
print "Something goes here"


But this code replace
print "Anything goes here"
to
print(
, How to capture whole string and replace last quote to ")" a well?

Answer

Try this:

print\s+\"(.+)\"

and replace by this:

 print("\1")

Explanation

You can try this:

import re

regex = r"print\s+\"(.+)\""

test_str = ("print \"Anything goes here\"\n"
    "print \"Anything\" \n"
    "print \"Something goes here\" ")

subst = " print(\"\\1\")"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)
Comments