title: python how to test field contents with regex if
body: <p>I want to test the contents of a field in a line to see if that field contains \n. I have a field that has multiple occurrences of \n and I'm trying to find and replace all of them with '' or an empty in place of the \n but leave the rest of the contents of the field. There are other characters in the field as well but I'm specifically looking to get rid of these \n characters. </p>
  
  <p>Here's how I've coded it but I'm wondering if I'm using the best Python method and exactly how to test for the string value I'm searching for. </p>
  
  <pre><code>#!/usr/bin/env python
  import re
  
  inFile = open('/baddatafile.txt','r')
  
  for line in inFile:
     data = line.strip().split('\t')
  
     print 'before: %s' % (data[2])
     data[2] = re.sub(r'\n', '', data[2])
     print 'after: %s' % (data[2])
  </code></pre>
  
  <p>This removes one of the occurrences but only the middle one and there are three occurrences in the record I'm using as a test record.</p>
  
  <p>Here's a sample input record: </p>
  
  <pre><code>&lt;textarea cols='60' rows='8'&gt;This \\n is my first \\nstatement one.\\n&lt;div&gt;
  </code></pre>
  
  <p>And sample output that I'd like: either:</p>
  
  <pre><code>&lt;textarea cols='60' rows='8'&gt;This is my first statement one.&lt;div&gt;
  </code></pre>
  
  <p>or: an empty field</p>