title: Recursively create a new line break after nth character for a given block of text
body: <p>I've written a small script that creates a new line break after a certain character limit has been reached. Now the  problem is that the script outputs the text starting at the end of the text. I can't seem to figure out how to make the text print out in the correct order without making the script more complicated. I'm doing this an exercise to better understand recursion. </p>
  
  <p><strong>Here is the code:</strong></p>
  
  <pre><code>def insertNewlines(text, lineLength):
  
      if len(text) &lt;= lineLength:
          return text
      else:
          return insertNewlines(text[lineLength:], lineLength) + '\n' + text[:lineLength]
  </code></pre>
  
  <p><strong>Here is the test output for a lineLength of 15:</strong></p>
  
  <pre><code>length.  
  e desired line   
  s or exceeds th  
  ord that reache  
  n' after each w  
  e character  '\  
  Insert a newlin  
  ewriter would.   
  e text as a typ  
  length, wrap th  
  a desired line   
  Given text and  
  </code></pre>
  
  <p><strong>The actual input:</strong>  </p>
  
  <pre><code>text = "Given text and a desired line length, wrap the text as a typewriter would. Insert a newline character  '\\n' after each word that reaches or exceeds the desired line length."
  </code></pre>
  
  <p>EDIT:
  Modified the code based on the suggestion below so that it wraps the words correctly:</p>
  
  <pre><code>    if len(text) &lt;= lineLength:
      return text
  elif text[lineLength] != ' ':
      return insertNewlines(text[:], lineLength + 1)
  else:
      return text[:lineLength] + '\n' + insertNewlines(text[lineLength + 1:], lineLength)
  </code></pre>
  
  <p><strong>Here is the new output:</strong><br>
  Given text and a<br>
  desired line length,<br>
  wrap the text as a typewriter<br>
  would. Insert a newline character<br>
   '\n' after each word that reaches<br>
  or exceeds the desired line length.  </p>