Squezing in replacements into strings

Adriano Ferreira a.r.ferreira at gmail.com
Mon Apr 25 08:23:28 EDT 2005


As Peter Otten said, sub() is probably what you want. Try:

---------------------------------------------------
import re

def _ok(matchobject):
    # more complicated stuff happens here
    return 1

def _massage(word):
    return "_" + word + "_"


def _massage_or_not(matchobj):
    if not _ok(matchobj):
        return matchobj.group(0) 
    else:
        word = matchobj.group(0)
        return _massage(word)


text = "don't allow the fuck swear word"
    
rtext = re.sub(r'fuck', _massage_or_not, text)
print rtext
---------------------------------------------------

No need to hassle with the changing length of the replaced string.

Best regards,
Adriano.



More information about the Python-list mailing list