title: Python 2.6+ str.format() and regular expressions
body: <p>Using <code>str.format()</code> is the new standard for formatting strings in Python 2.6, and Python 3. I've run into an issue when using <code>str.format()</code> with regular expressions.</p>
  
  <p>I've written a regular expression to return all domains that are a single level below a specified domain or any domains that are 2 levels below the domain specified, if the 2nd level below is www...</p>
  
  <p>Assuming the specified domain is delivery.com, my regex should return a.delivery.com, b.delivery.com, www.c.delivery.com ... but it should not return x.a.delivery.com.</p>
  
  <pre><code>import re
  
  str1 = "www.pizza.delivery.com"
  str2 = "w.pizza.delivery.com"
  str3 = "pizza.delivery.com"
  
  if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str1): print 'String 1 matches!'
  if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str2): print 'String 2 matches!'
  if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}delivery.com$', str3): print 'String 3 matches!'
  </code></pre>
  
  <p>Running this should give the result:</p>
  
  <pre><code>String 1 matches!
  String 3 matches!
  </code></pre>
  
  <p>Now, the problem is when I try to replace delivery.com dynamically using str.format...</p>
  
  <pre><code>if (re.match('^(w{3}\.)?([0-9A-Za-z-]+\.){1}{domainName}$'.format(domainName = 'delivery.com'), str1): print 'String 1 matches!'
  </code></pre>
  
  <p>This seems to fail, because the <code>str.format()</code> expects the <code>{3}</code> and <code>{1}</code> to be parameters to the function. (I'm assuming)</p>
  
  <p>I could concatenate the string using + operator</p>
  
  <pre><code>'^(w{3}\.)?([0-9A-Za-z-]+\.){1}' + domainName + '$'
  </code></pre>
  
  <p>The question comes down to, is it possible to use <code>str.format()</code> when the string (usually regex) has "<strong>{n}</strong>" within it?</p>