ActiveState Code

Recipe 414870: Align text string using spaces between words to fit specified width


Python 2.3 module textwrap can justify text in three modes: left/right/center. Sometimes 'align' mode become more useful.

Python
 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'''
align_string.py

Align string with spaces between words to fit specified width

Author: Denis Barmenkov <denis.barmenkov@gmail.com>

Copyright: this code is free, but if you want to use it, 
           please keep this multiline comment along with function source. 
           Thank you.

2005-05-22 13:27 
'''
import re, string, textwrap

def items_len(l):
    return sum([ len(x) for x in l] )

lead_re = re.compile(r'(^\s+)(.*)$')

def align_string(s, width):
    global lead_re
    # detect and save leading whitespace
    m = lead_re.match(s) 
    if m is None:
        left, right, w = '', s, width
    else:
        left, right, w = m.group(1), m.group(2), width - len(m.group(1))

    items = string.split(right)

    # add required pace to each words, exclude last
    for i in range(len(items)-1):
        items[i] += ' '

    # number of spaces to add
    left_count = w - items_len(items)
    while left_count > 0 and len(items) > 1:
        for i in range(len(items)-1):
            items[i] += ' '
            left_count -= 1
            if left_count < 1:  
                break
    res = left + ''.join(items)
    return res

s = 'Contributors whose recipes are used in the book will receive a complimentary copy of the Second Edition. A portion of all royalties will go to the non-profit Python Software Foundation.'

width = 30

splitted = textwrap.wrap(s, width) 
print 'textwrap:\n%s\n' % '\n'.join(splitted)

wrapped = [ align_string(x, width) for x in splitted ]

print 'textwrap & align_string:\n%s\n' % '\n'.join(wrapped)

'''
=====================
Script output:
=====================

textwrap:
Contributors whose recipes are
used in the book will receive
a complimentary copy of the
Second Edition. A portion of
all royalties will go to the
non-profit Python Software
Foundation.

textwrap & align_string:
Contributors whose recipes are
used  in the book will receive
a  complimentary  copy  of the
Second  Edition.  A portion of
all  royalties  will go to the
non-profit   Python   Software
Foundation.
'''

Comments

  1. 1. At 4:15 a.m. on 15 dec 2005, Madan Sreenivasan said:

    Using this recipe in summarydesk. Hi Denis, I find this code useful. I plan to use this in the tool am developing (http://summarydesk.tigris.org). Thank you for the same.

    Regards, Madan.

Sign in to comment