1

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.

1
  • perhaps posting the code for insertNewlines would herlp ... Commented Mar 17, 2013 at 12:50

2 Answers 2

5

Don't re-invent the wheel, use the textwrap library instead:

import textwrap

wrapped = textwrap.fill(text, 38)

Your own code does not handle the case where no space has been found and spacja returns -1.

Sign up to request clarification or add additional context in comments.

2 Comments

you might mean textwrap.fill().
@J.F.Sebastian: Indeed, .wrap() returns a list, .fill() joins them with newlines.
1

You are missing the case when find returns -1 (i.e. not found).

Try:

if len(text) <= lineLength:
    return text
else:
    x = spacja(text, lineLength)
    if x == -1:
        return text
    else:
        return text[:x] + '\n' + insertNewlines(text[x+1:], lineLength)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.