简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM