Iteration within re.sub()?

Mark McEahern marklists at mceahern.com
Mon Dec 13 22:09:03 EST 2004


Bryant Huang wrote:

>Hi,
>
>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:

#!/usr/bin/env python

import re

class Counter:
    def __init__(self):
        self.count = -1
    def increment(self, matchObject):
        self.count += 1
        return str(self.count)

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 mailing list