在学习 Python 正则表达式时,我想将所有 Python 2x 之类的打印函数替换为 Python 3x,例如使用 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)
py2.py的内容是:
print "Anything goes here"
print "Anything"
print "Something goes here"
但是这段代码将 print "Anything goes here"
替换为 print(
, How to capture whole string and replace last quote to ")"a well?
最佳答案
您想在您的搜索中使用对匹配组的引用:
re.sub(r'print\s+"(.*)"', r'print("\1")', matter)
用作:
>>> 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")
请注意,如果您的目标是将 python2 代码修改为与 python3 兼容,则 2to3
utility 已经存在它包含在 python 本身中。
关于python - 在 python 中使用 re.sub 进行字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380567/