为什么在Python中更改字符串中的行(\n)不起作用?

1 python string line

在大多数情况下,它完成了这项工作,但有时(我很难精确,它依赖于什么)它会陷入无限循环,因为它不会切割文本字符串.

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)
Run Code Online (Sandbox Code Playgroud)

适用于我尝试过的所有情况除外

 insertNewlines('Random text to wrap again.', 5)
Run Code Online (Sandbox Code Playgroud)

和

insertNewlines('mubqhci sixfkt pmcwskvn ikvoawtl rxmtc ehsruk efha cigs itaujqe pfylcoqw iremcty cmlvqjz uzswa ezuw vcsodjk fsjbyz nkhzaoct', 38)
Run Code Online (Sandbox Code Playgroud)

我不知道为什么.

Mar*_*ers 5

不要重新发明轮子,而是使用textwrap库:

import textwrap

wrapped = textwrap.fill(text, 38)
Run Code Online (Sandbox Code Playgroud)

您自己的代码不处理没有找到空格并spacja返回-1的情况.