title: Python 3 print() to a variable
body: <p>In Python 3, you can use the print function to write the data to a file (e.g. <code>print('my data', file=my_open_file)</code>. This is well and good (and very cool). But can you <code>print</code> to a (string?) variable? If so, how?</p>
  
  <p>In my specific use case, I am trying to avoid writing the data to a tempfile on disk just to turn and read that tempfile.</p>
  
  <p><strong>Edit:</strong> I'm can't just assign because my source data isn't a string, rather it's part of the html document tree as extracted by BeautifulSoup. Once I have the document tree extracted, I'm going to process it line by line.</p>
  
  <hr>
  
  <p><strong>My Code</strong>: (working now!)</p>
  
  <pre><code>with open("index.html", "r") as soup_file:
      soup = BeautifulSoup(soup_file)
  THE_BODY = soup.find('body')
  not_file = io.StringIO()
  print(THE_BODY, file = not_file)    # dump the contents of the &lt;body&gt; tag into a file-like stream
  with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
      for line in not_file2.getvalue().split('\n'):
          print("headerblock += '{}'".format(line), file = HEADER_JS)
  </code></pre>
  
  <hr>
  
  <p><strong>Better, Working Code</strong>:</p>
  
  <pre><code>with open("index.html", "r") as soup_file:
      soup = BeautifulSoup(soup_file)
  with codecs.open('header.js', "w", "utf-8") as HEADER_JS:
      for line in str(soup.find('body')).split('\n'):
          print("headerblock += '{}'".format(line), file = HEADER_JS)
  </code></pre>