-3
def insertNewLine(text, lenght):

    if len(text) < lenght:
        return text
    else:
        print text[:lenght]
        return (text[:lenght]+'\n'+ insertNewLine(text[lenght:],lenght))

but the problem is that word is dividing by my program .. that should not happen.. e.g.

=> Input :

"Random text to wrap again." and Lenght: 5

=> My Output:

Rando
m tex
t to
wrap
again
.

=> Expected Output:

Random
text
to wrap
again.
DSM
  • 342,061
  • 65
  • 592
  • 494
Ajinkya
  • 11
  • 1
  • 4

4 Answers4

1

It looks like you need to wrap on whole words after a certain length, and ignoring spaces; I'd do something like this:

def wrap(text, length):
    words = text.split()
    lines = []
    line = ''
    for w in words:
        if len(w) + len(line) > length:
            lines.append(line)
            line = ''
        line = line + w + ' '
        if w is words[-1]: lines.append(line)
    return '\n'.join(lines)

This basically works by splitting the text into whole words, and then assembling lines of them up to your wrap length. That way you don't have to figure out if you're trying to break in the middle of a word. I didn't bother to check whether your length is shorter than your longest word, but that's a consideration as well.

toxotes
  • 1,386
  • 14
  • 20
  • Ah. That's not at all clear from your question -- you may want to note that you're specifically looking for a recursive solution, and describe why that's the case. – toxotes Nov 03 '12 at 12:22
  • I'm afraid you didn't. You mention recursion in the title and of course show it in your code, but there's no indication that it's important to the solution in the question itself or in the question tags. The way I personally read it is that you need to word-wrap a string, and you happened to try recursion but didn't get the results you want. I do mean this as constructive criticism in case it's not clear -- in a case like this where you're trying to understand a specific technique through an example, ask about the technique and not the example. – toxotes Nov 03 '12 at 14:13
0

This is a posible solution to your problem, I use re python module to put \n characters in the right place.

import re
def insertNewLine(text, lenght):
    return re.sub('((.*){' + str(lenght-1) + ',}?)\s', '\g<1>\n', text)

if __name__ == "__main__":
    print insertNewLine("Random text to wrap again.", 5)

>>>python test.py 
Random
text
to wrap
again.
jvallver
  • 2,230
  • 2
  • 11
  • 20
  • showing wrong result for input : insertNewlines('While I expect new intellectual adventures ahead, nothing will compare to the exhilaration of the world-changing accomplishments that we produced together.', 15) – Ajinkya Nov 03 '12 at 09:08
  • insertNewlines('While I expect new intellectual adventures ahead, nothing will compare to the exhilaration of the world-changing accomplishments that we produced together.', 15) – Ajinkya Nov 03 '12 at 09:10
  • Sorry, did not foresee that could have characters other than letters. I edited my answer. – jvallver Nov 03 '12 at 19:24
  • I don't have this problem, be sure lenght is of type int. What version of python are you using? – jvallver Nov 04 '12 at 16:44
0
def insertNewLine(text, lenght):

if len(text) < lenght:
    return text
else:
    print text[:lenght]
    return (text[:lenght]+'\n'+ insertNewLine(text[lenght:],lenght))

"Random text to wrap again." and Lenght: 5

The problem is that you are saying with

'\n'

That you want a new line ever 5 characters. The word Random has 6 which is why it is being cut at Rando. Also remember that the spaces count as a character as well. So when your recursion goes through it is simply counting 5 characters and then inserting a new line every 5.

Alex
  • 542
  • 5
  • 24
  • so.. whats the solution for that.?? – Ajinkya Nov 03 '12 at 09:05
  • now that im looking at this... this looks like homework from the MIT edx site: 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. lineLength: the number of characters to include on a line before wrapping the next word. returns: a string, with newline characters inserted appropriately. """ – Alex Nov 05 '12 at 17:30
0
def insertNewline(text, length):
    '''
    This function can only be applied to normal text.
    '''
    if len(text) <= length:
        print(text)
        return
    elif text[length - 1] == ' ':
        print(text[:length - 1])
        return insertNewline(text[(length):], length)
    elif text[length] == ' ':
        print(text[:length])
        return insertNewline(text[(length + 1):], length)        
    else:
        i = 0
        while text[length + i] != ' ' and text[length + i] != ',' and text[length + i] != '.':
            i += 1
        if text[length + i] == ' ':
            print(text[:(length + i)])
            return insertNewline(text[(length + i + 1):], length)
        else:
            print(text[:(length + i + 1)])
            return insertNewline(text[(length + i + 2):], length)

This code works correctly with normal text, by which I mean simple English sentences with only ',' and '.' as punctuations, and after each punctuation there is only one space, just as normal essay writing. If you want to apply this code to more complete text, I think you can update this code by yourself. I use "recursion" as you required in your question. I think this code should be helpful for you. I'm not an expert in python, and still in the learning process. Hope you can get what you want from my answer.