The problem is with the order of recursive call. It should be at the tail of the function to achieve what you want. Try this:
def insertNewlines(text, lineLength):
if len(text) <= lineLength:
return text
else:
return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)
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."
print insertNewlines(text, 15)
Output:
Given text and
a desired line
length, wrap th
e text as a typ
ewriter would.
Insert a newlin
e character '\
n' after each w
ord that reache
s or exceeds th
e desired line
length.