🛠️ToolsShed

文字换行

在指定列宽处换行长文本,支持单词换行和字符换行选项。

20200

常见问题

代码实现

def word_wrap(text: str, width: int = 80, hard: bool = False) -> str:
    """Wrap text to the specified width.

    Args:
        text:  Input text (may contain existing newlines).
        width: Maximum line length in characters.
        hard:  If True, break mid-word at exactly 'width' chars.
    """
    import textwrap
    if hard:
        # Hard wrap: split each existing line at 'width' chars
        lines = []
        for line in text.splitlines(keepends=True):
            while len(line) > width:
                lines.append(line[:width] + "\n")
                line = line[width:]
            lines.append(line)
        return "".join(lines)
    else:
        # Soft wrap: only break at whitespace
        paragraphs = text.split("\n\n")
        wrapped = [textwrap.fill(p, width=width) for p in paragraphs]
        return "\n\n".join(wrapped)


text = ("The quick brown fox jumps over the lazy dog. "
        "Pack my box with five dozen liquor jugs. "
        "How vexingly quick daft zebras jump!")

print(word_wrap(text, width=40))

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.