In most cases it does the job, but sometimes (it's hard for my to precise, what does it depend on) it falls into an infinite loop, as it doesn't slice the text string.
def insertNewlines(text, lineLength):
"""
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.
text: a string containing the text to wrap.
line_length: the number of characters to include on a line before wrapping
the next word.
returns: a string, with newline characters inserted appropriately.
"""
def spacja(text, lineLength):
return text.find(' ', lineLength-1)
if len(text) <= lineLength:
return text
else:
x = spacja(text, lineLength)
return text[:x] + '\n' + insertNewlines(text[x+1:], lineLength)
works with all cases I tried except for
insertNewlines('Random text to wrap again.', 5)
and
insertNewlines('mubqhci sixfkt pmcwskvn ikvoawtl rxmtc ehsruk efha cigs itaujqe pfylcoqw iremcty cmlvqjz uzswa ezuw vcsodjk fsjbyz nkhzaoct', 38)
I have no idea why.