title: Python regex string escaping for re.sub replace argument?
body: <p>Using <code>re</code> module it's possible to use escaping for the replace pattern. eg:</p>
  
  <pre class="lang-py prettyprint-override"><code>def my_replace(string, src, dst):
      import re
      return re.sub(re.escape(src), dst, string)
  </code></pre>
  
  <p>While this works for the most-part, the <code>dst</code> string may include <code>"\\9"</code> for example.</p>
  
  <p>This causes an issue:</p>
  
  <ul>
  <li><code>\\1</code>, <code>\\2</code> ... etc in <code>dst</code>, literals will be interpreted as groups.</li>
  <li>using <code>re.escape(dst)</code> causes <code>.</code> to be changed to <code>\.</code>.</li>
  </ul>
  
  <p>Is there a way to escape the destination without introducing redundant character escaping?</p>
  
  <hr>
  
  <p>Example usage:</p>
  
  <pre><code>&gt;&gt;&gt; my_replace("My Foo", "Foo", "Bar")
  'My Bar'
  </code></pre>
  
  <p>So far, so good.</p>
  
  <hr>
  
  <pre><code>&gt;&gt;&gt; my_replace("My Foo", "Foo", "Bar\\Baz")
  ...
  re.error: bad escape \B at position 3
  </code></pre>
  
  <p>This tries to interpret <code>\B</code> as having a special meaning.</p>
  
  <hr>
  
  <pre><code>&gt;&gt;&gt; my_replace("My Foo", "Foo", re.escape("Bar\\Baz"))
  'My Bar\\Baz'
  </code></pre>
  
  <p>Works!</p>
  
  <hr>
  
  <pre><code>&gt;&gt;&gt; my_replace("My Foo", "Foo", re.escape("Bar\\Baz."))
  'My Bar\\Baz\\.'
  </code></pre>
  
  <p>The <code>.</code> gets escaped when we don't want that.</p>
  
  <hr>
  
  <p>While in this case <code>str.replace</code> can be used, the question about destination string remains useful since there may be times we want to use other features of <code>re.sub</code> such as the ability to ignore case.</p>