Welcome, guest | Sign In | My Account | Store | Cart

Word_wrap.py provides a simple, brute-force, solution to word-wrapping text to a given width. It was invented for the use by my xgetopt module.

Python, 64 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python
#
# word_wrap.py
#
# Copyright (c) 2001 Alan Eldridge. All rights reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the "Artistic License" which is
# distributed with the software in the file LICENSE.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the Artistic
# License for more details.
#
# Thank you.
#
# Alan Eldridge 2001-09-16 alane@wwweasel.geeksrus.net
#
# $Id: word_wrap.py,v 1.4 2001/10/14 05:04:37 alane Exp $
#
# 2001-09-16 alane@wwweasel.geeksrus.net
#

import string

def wrap_str(str, max):
    ll = []
    lines = string.split(str, '\n')
    if len(lines) > 1:
        return wrap_list(lines, max)
    words = string.split(lines[0])
    for i in range(len(words)):
        if len(words[i]) == 0:
            del words[i]
    while len(words):
        cc = 0
        cw = 0
        for w in words:
            tmp = (cc > 0) + cc + len(w)
            if tmp > max:
                break
            cc = tmp
            cw = cw + 1
        if cw == 0:
            # must break word in middle
            ll.append(words[cw][:max-1] + '+')
            words[cw] = words[cw][max-1:]
        else:
            ll.append(string.join(words[:cw]))
            words = words[cw:]
    return ll

def wrap_list(lines, max):
    ll = []
    for l in lines:
        if len(ll):
            ll.append('')
        ll = ll + wrap_str(l, max)
    return ll

#
#EOF
##

This code was invented for use by my xgetopt module. There are no suprises here, no cases for making things look better in extreme cases. It was the simplest thing that did the job.

Word_wrap is released under the Artistic License as distributed in the latest stable version of Perl (5.6.1).

Revised 2001/10/14: paragraph separator is now passed in to wrap_str and wrap_list. It defaults to a single newline, so old code is not broken. Try a separator of '\n\n' for wrapping formatted text that uses blank lines to separate paragraphs. Also, empty "words" are discarded now.

Created by Alan Eldridge on Sun, 7 Oct 2001 (PSF)
Python recipes (4591)
Alan Eldridge's recipes (2)

Required Modules

Other Information and Tasks