Iteration within re.sub()?
marklists at mceahern.com
Tue Dec 14 04:09:03 CET 2004
Bryant Huang wrote:
>Is it possible to perform iteration within the re.sub() function call?
Sure. As the docs note:
If repl is a function, it is called for every non-overlapping occurrence
of pattern. The function takes a single match object argument, and
returns the replacement string. For example:
self.count = -1
def increment(self, matchObject):
self.count += 1
text = "abbababbaaaaaabbaaa"
expected = "a01a2a34aaaaaa56aaa"
# Replace all b's with an integer that increments from 0.
c = Counter()
pat = re.compile("(b)")
actual = pat.sub(c.increment, text)
assert expected == actual
More information about the Python-list