How to format an array of strings in lines with maxWidth without breaking the words in Python

1 Answer

0 votes
def format_lines(words, max_width):
    result = []
    current_line = ""
    current_length = 0

    for word in words:
        word_len = len(word)

        # If adding this word exceeds max_width, push current line
        if current_length + (0 if current_line == "" else 1) + word_len > max_width:
            result.append(current_line)
            current_line = word
            current_length = word_len
        else:
            if current_line:
                current_line += " "
                current_length += 1
            current_line += word
            current_length += word_len

    # Push the last line if not empty
    if current_line:
        result.append(current_line)

    return result


def main():
    words = ["This", "is", "a", "programming", "example", "of", "text", "wrapping"]
    max_width = 12

    lines = format_lines(words, max_width)

    for line in lines:
        print(f"\"{line}\"")


if __name__ == "__main__":
    main()



'''
run:

"This is a"
"programming"
"example of"
"text"
"wrapping"

'''

 



answered Dec 2, 2025 by avibootz

Related questions

...