Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String replacements using re.sub in python

Tags:

python

regex

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?

like image 204
Yethrosh Avatar asked Jul 19 '26 00:07

Yethrosh


2 Answers

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.

like image 171
Bakuriu Avatar answered Jul 20 '26 13:07

Bakuriu


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)
like image 43
Rizwan M.Tuman Avatar answered Jul 20 '26 15:07

Rizwan M.Tuman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!