If replacement is a string, any backslash escapes in it are processed. That is,$_{
}$ is converted to a single newline char- acter, \r is converted to a carriage return, and so forth. Unknown escapes such as \& are left alone. Backreferences, such as$_{\6}$ , are replaced with the substring matched by the corresponding group in the RE. This lets you incorporate portions of the original text in the resulting replacement string. This example matches the word section followed by a string enclosed in $_{{}$, $_{}}$, and changes section to $_{subsection}$: >>> p =re.compile( 'section{ ( [^}]* ) } ', re.VERBOSE) >>> p.sub(r'subsection{ \1}','section {First} section {second} ') 'subsection{First} subsection{second}' >>> p =re.compile( 'section{ (?P<name> [^}]* ) } ', re.VERBOSE) >>> p.sub(r'subsection{ \1}','section {First} ') 'subsection{First}' >>> p.sub(r'subsection{ \g<1>} ','section {First} ') 'subsection{First}' >>> p.sub(r'subsection{ \g<name>} ','section {First} ') 'subsection{First}' There’s also a syntax for referring to named groups as defined by the$_{(?P<name>...)}$ syntax. \g<name> will use the substring matched by the group named name , and \g<number> uses the corresponding group number. \g<2> is therefore equivalent to$_{\2}$ , but isn’t ambiguous in a replacement string such as$_{\g<2>0}$ . ($_{\20}$ would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character '0' .) The following substitutions are all equivalent, but use all three variations of the replacement string. replacement can also be a function, which gives you even more control. If replacement is a function, the function is called for every non-overlapping occurrence of pattern . On each call, the function is passed a match object argument for the match and can use this information to compute the desired replacement string and return it. In the following example, the replacement function translates decimals into hexadecimal: When using the module-level$_{re.sub()}$ function, the pattern is passed as the first argument. The pattern may be provided as an object or as a string; if you need to specify regular expression flags, you must either use a pattern object as the first parameter, or use embedded modifiers in the pattern string, e.g. sub("(?i)b+", "x", "bbbb BBBB") returns$_{'x x'}$ . 16 >>>def hexrepl(match): ... "Return the hex string for a decimal number" ... value=int(match.group()) ... return hex(value) ... >>> p =re.compile( r'\d+') >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code. ') 'Call 0xffd2 for printing, 0xc000 for user code.'