Regular expression help

Harvey Thomas hst at
Tue Apr 1 10:08:29 CEST 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:


def mysub(x):
    return '\n' +

myregex.sub(mysub, mystring)


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

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


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

More information about the Python-list mailing list