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

标签 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)

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

 insertNewlines('Random text to wrap again.', 5)

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

我不知道为什么。

最佳答案

不要重新发明轮子,使用 textwrap library相反:

import textwrap

wrapped = textwrap.fill(text, 38)

您自己的代码无法处理未找到空间且 spacja 返回 -1 的情况。

关于python - 为什么在 Python (\n) 中更改字符串中的行不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15460863/

相关文章:

python - Pandas groupby - 按列值扩展平均值

python - 如何使用 SQLAlchemy 将数据从 SQL_ASCII 复制到 UTF8 postgresql 数据库?

c - 返回 C 中的字符串数组

android - 如何删除 Android 中的画线

javascript - clearRect 函数不清除 Canvas

r - 连接散点图中的所有点(可能的组合)

python - 从 flask-admin 的模型 View 中删除/隐藏/删除 "with selected" View

javascript - 翻转匹配子串

java - 如何在 Java 中比较字符串?

Python - 通过 X 点拟合多项式(多维)