Split a String into Multiple Lines by Width in Python

Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

27 lines
Python 3.9+
def split_message(text, max_width):
    words = text.split()
    rows = []
    current_row = []

    for word in words:
        if len(" ".join(current_row + [word])) > max_width:
            rows.append(" ".join(current_row))
            current_row = [word]
        else:
            current_row.append(word)

    if current_row:
        rows.append(" ".join(current_row))

    return rows


if __name__ == "__main__":
    message = "This is a demo message that needs to be split into multiple rows for better readability"
    max_width = 20
    result = split_message(message, max_width)
    print(f"Input message: '{message}'")
    print(f"Max width: {max_width}")
    print("Split rows:")
    for i, row in enumerate(result, 1):
        print(f"  Row {i}: '{row}' (length {len(row)})")

Output

stdout
Input message: 'This is a demo message that needs to be split into multiple rows for better readability'
Max width: 20
Split rows:
  Row 1: 'This is a demo' (length 14)
  Row 2: 'message that needs' (length 19)
  Row 3: 'to be split into' (length 17)
  Row 4: 'multiple rows for' (length 17)
  Row 5: 'better readability' (length 19)

How it works

The algorithm splits the text into individual words, then greedily adds words to a row as long as the total length stays within max_width. When adding a word would exceed the limit, the current row is finalized and a new row begins with that word. The join operation is used repeatedly to check lengths, which is simple and readable but could be optimized for very large texts. This is a classic greedy word-wrap approach that aims to place as many words per row as possible without breaking words.

Common mistakes

  • Not handling single words longer than max_width, which would create an over-length row
  • Forgetting to flush the last row after the loop ends
  • Using the length of a word list instead of the joined string when checking row width

Variations

  1. Use textwrap.wrap from the standard library to get a similar result with built-in handling
  2. Replace the greedy check with a running character count to avoid repeated join operations

Real-world use cases

  • Formatting terminal output or log messages so each line fits within a console width.
  • Creating readable SMS or chat message chunks that respect a character limit per message.
  • Generating printable text reports where column widths must stay under a fixed page width.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.