'''
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.
'''