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?
You want to use references to the matching groups in your sostitution:
re.sub(r'print\s+"(.*)"', r'print("\1")', matter)
Used as:
>>> import re
>>> matter = """
... print "Anything goes here"
... print "Anything"
... print "Something goes here"
... """
>>> print(re.sub(r'print\s+"(.*)"', r'print("\1")', matter))
print("Anything goes here")
print("Anything")
print("Something goes here")
Note that if your goal is to modify python2 code to be python3 compatible there already exist the 2to3 utility which comes included with python itself.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With