Insert New Lines

With recursion, thinking is simple:

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. 
    if len(text) <= lineLength:
        return text
    elif text[lineLength - 1] == ' ':
        return text[:lineLength] + "\n" + insertNewlines(text[lineLength:], lineLength)
        spaceAt = text[lineLength:].find(' ')
        return text[:spaceAt+lineLength] + "\n" + insertNewlines(text[lineLength+spaceAt+1:], lineLength)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s