Yethrosh Yethrosh - 11 months ago 51
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


import re

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

Matter of is:

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

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

Answer Source

Try this:


and replace by this:



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)