You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python按长度切割句子:实现超长文本按指定长度换行拆分

Python: Split Sentence into Lines by Max Length (Space-Separated)

Got it, let's tackle this problem: you need to split a long sentence into multiple lines where each line's total length doesn't exceed a given limit, and you only want to split at spaces (so no broken words). Here's a practical, easy-to-follow function that gets the job done, plus an example using your sample input.

Solution Code

def split_sentence_by_length(sentence, max_length):
    # Split the sentence into individual words
    words = sentence.split()
    lines = []
    current_line_words = []
    current_line_length = 0

    for word in words:
        word_len = len(word)
        # Calculate length needed to add this word (plus a space if line isn't empty)
        needed_length = current_line_length + word_len + (1 if current_line_words else 0)

        if needed_length <= max_length:
            # Word fits, add to current line
            current_line_words.append(word)
            current_line_length = needed_length
        else:
            # Word doesn't fit—finalize current line and start a new one
            lines.append(' '.join(current_line_words))
            current_line_words = [word]
            current_line_length = word_len

    # Don't forget to add the last line of words
    if current_line_words:
        lines.append(' '.join(current_line_words))
    
    return lines

# Test with your example
original = "This sentence is way too long."
max_char_limit = 15
split_lines = split_sentence_by_length(original, max_char_limit)

# Print the result
print("Original sentence:", original)
print(f"\nSplit into lines (max length {max_char_limit}):")
for idx, line in enumerate(split_lines, 1):
    print(f"Line {idx}: '{line}' (length: {len(line)})")

How It Works

Let's break down what the function does:

  • Split into Words: First, we split the input sentence into a list of words using spaces as separators—this ensures we only work with full words, no partial splits.
  • Build Lines Iteratively: We loop through each word, checking if adding it to the current line (plus a space if the line isn't empty) would exceed the max length.
    • If it fits, we add the word to the current line and update the line's total length.
    • If it doesn't fit, we save the current line to our result list, then start a new line with the current word.
  • Finalize Last Line: After the loop, we make sure to add the remaining words (the last line) to our result.

Example Output

When you run the code with your sample input, you'll get this output:

Original sentence: This sentence is way too long.

Split into lines (max length 15):
Line 1: 'This sentence' (length: 13)
Line 2: 'is way too' (length: 10)
Line 3: 'long.' (length: 5)

Edge Case Note

What if a single word is longer than the max length? The function will still add it as a single line (since we can't split at spaces). If you need to handle this scenario (like truncating the word or throwing a warning), you can add an extra check at the start of the loop to handle those cases.

内容的提问来源于stack exchange,提问作者helpme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 03:42:54