Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:
And then concatenate the
start group with the new data for
replace and then the
Is there a better method for this?
Look in the Python re documentation for lookaheads
(?=...) and lookbehinds
(?<=...) -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.
>>> import re >>> s = "start foo end" >>> s = re.sub("foo", "replaced", s) >>> s 'start replaced end' >>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s) >>> s 'start can use a callable for the replaced text too end' >>> help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used.