title: Replacing named capturing groups with re.sub
body: <p>I want to replace the text of matched re patterns in a string and can do this using <code>re.sub()</code>. If I pass it a function as the <code>repl</code> argument in the call it works as desired, as illustrated below:</p>
  <pre><code>from __future__ import print_function
  import re
  
  pattern = r'(?P&lt;text&gt;.*?)(?:&lt;(?P&lt;tag&gt;\w+)&gt;(?P&lt;content&gt;.*)&lt;/(?P=tag)&gt;|$)'
  
  my_str = &quot;Here's some &lt;first&gt;sample stuff&lt;/first&gt; in the &quot; \
              &quot;&lt;second&gt;middle&lt;/second&gt; of some other text.&quot;
  
  def replace(m):
      return ''.join(map(lambda v: v if v else '',
                          map(m.group, ('text', 'content'))))
  
  cleaned = re.sub(pattern, replace, my_str)
  print('cleaned: {!r}'.format(cleaned))
  </code></pre>
  <p>Output:</p>
  <pre class="lang-none prettyprint-override"><code>cleaned: &quot;Here's some sample stuff in the middle of some other text.&quot;
  </code></pre>
  <p>However from the documentation it sounds like I should be able to get the same results by just passing it a replacement string with references to the named groups in it. However my attempt to do that didn't work because sometimes a group is unmatched and the value returned for it is <code>None</code> (rather than an empty string <code>''</code>).</p>
  <pre><code>cleaned = re.sub(pattern, r'\g&lt;text&gt;\g&lt;content&gt;', my_str)
  print('cleaned: {!r}'.format(cleaned))
  </code></pre>
  <p>Output:</p>
  <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
    File &quot;test_resub.py&quot;, line 21, in &lt;module&gt;
      cleaned = re.sub(pattern, r'\g&lt;text&gt;\g&lt;content&gt;', my_str)
    File &quot;C:\Python\lib\re.py&quot;, line 151, in sub
      return _compile(pattern, flags).sub(repl, string, count)
    File &quot;C:\Python\lib\re.py&quot;, line 278, in filter
      return sre_parse.expand_template(template, match)
    File &quot;C:\Python\lib\sre_parse.py&quot;, line 802, in expand_template
      raise error, &quot;unmatched group&quot;
  sre_constants.error: unmatched group
  </code></pre>
  <p>What am I doing wrong or not understanding?</p>