我有以下声明的文件。
start < some 50 words > End //need to work only on these types
start < some 50 words >
start < some 50 words > End
start < some 50 words >
< some 50 words > End
...此模式重复10000次。 我想用
替换在开头'和'结尾'开头的行start2 <same 50 words > End2.
我需要在两者之间保持相同的单词只需修改开始和结束。
答案 0 :(得分:1)
import re
data = """start < some 50 words > End
start < some 50 words >
start < some 50 words > End
start < some 50 words >
< some 50 words > End
"""
print re.sub('start(.*)End', 'start2\g<1>End.', data)
打印:
start2 < some 50 words > End.
start < some 50 words >
start2 < some 50 words > End.
start < some 50 words >
< some 50 words > End
答案 1 :(得分:1)
正则表达式比你需要解决这个问题更多的工作 - 使用普通的旧字符串方法可以更简单地完成:
def ReplaceStartEnd(s):
... if s.startswith("start") and s.endswith("End"):
... return "start2" + s[5:-3] + "End2"
... else:
... return s