title: Normalize whitespace with Python
body: <p>I'm building a data extract using <a href="https://scrapy.org/" rel="noreferrer">scrapy</a> and want to normalize a raw string pulled out of an HTML document. Here's an example string:</p>
  
  <pre><code>  Sapphire RX460 OC  2/4GB
  </code></pre>
  
  <p>Notice two groups of two whitespaces preceeding the string literal and between <code>OC</code> and <code>2</code>.</p>
  
  <p>Python provides trim as described in <a href="https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace-with-python">How do I trim whitespace with Python?</a> But that won't handle the two spaces between <code>OC</code> and <code>2</code>, which I need collapsed into a single space.</p>
  
  <p>I've tried using <a href="http://devdocs.io/xslt_xpath/xpath/functions/normalize-space" rel="noreferrer"><code>normalize-space()</code></a> from XPath while extracting data with my <a href="https://doc.scrapy.org/en/latest/topics/selectors.html" rel="noreferrer">scrapy Selector</a> and that works but the assignment verbose with strong rightward drift:</p>
  
  <pre><code>product_title = product.css('h3').xpath('normalize-space((text()))').extract_first()
  </code></pre>
  
  <p>Is there an elegant way to normalize whitespace using Python? If not a one-liner, is there a way I can break the above line into something easier to read without throwing an indentation error, e.g.</p>
  
  <pre><code>product_title = product.css('h3')
      .xpath('normalize-space((text()))')
      .extract_first()
  </code></pre>