Regular expression help

Harvey Thomas hst at empolis.co.uk
Tue Apr 1 03:08:29 EST 2003


Stephen Boulet wrote:
> How do I use the sub function to replace my match with my match 
> prepended by a newline?
> 
> Thanks.
> 
> -- Stephen
> 
Take advantage of the fact that the first argument of the sub method can be a function whose single argument is a match object:

(Untested)

def mysub(x):
    return '\n' + x.group(0)

myregex.sub(mysub, mystring)


or

myregex.sub(lambda x: '\n' + x.group(0), mystring)


For something as simple as this, I'd probably prefer the lambda form.

Harvey

_____________________________________________________________________
This message has been checked for all known viruses by the MessageLabs Virus Scanning Service.





More information about the Python-list mailing list