re.sub do not replace portion of match

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 2 18:10:28 CEST 2009

J Wolfe <vorticitywolfe at> wrote:

> Hi,
> Is there a way to flag re.sub not to replace a portion of the string?
> I have a very long string that I want to add two new line's to rather
> than one, but keep the value X:
> string = "test........X.\"  <-- note X is a value
> string = re.sub("test........X.\n.","test........X.\n\n.", string)
> This just replaces X with the replacement string.
> Thanks,
> Jonathan

Have you tried reading the documentation?

> Backreferences, such as \6, are replaced with the substring matched by 
> group 6 in the pattern.

and more such options in the docs.

More information about the Python-list mailing list