faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

4 of 7 people (57%) answered Yes
Recently 3 of 5 people (60%) answered Yes

Entry

Formatting text into columns

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 287, Magnus L. Hetland


"""
Packages: text.formatting
"""
"""
> Is there a Python module that will take a list of
> strings and wordwrap them columnwise, similar to
> Perl's format mechanism? For example, if supplied
> with the following strings
> 
>    "14/11/1999"
>    "Here is a a paragraph of text."
>    "Here is another paragraph of text."
> 
> and with appropriate specification of column
> widths and alignments, it could produce something
> like:
> 
>    14/11/2020   Here is a   Here is another
>                 paragraph   paragraph of text.
>                 of text.
Without really knowing whether there is such a module, I offer a
simple implementation of some of the functionality, which can easily
be extended:
"""
#---- format.py ----
left   = 0
center = 1
right  = 2
def align(line,width=70,alignment=left):
    space = width - len(line)
    if alignment == center:
        return ' '*(space/2) + line + \
               ' '*(space/2 + space%2)
    elif alignment == right:
        return ' '*space + line
    else:
        return line + ' '*space
def split(paragraph,width=70,alignment=left):
    result = []
    import string
    words = string.split(paragraph)
    current, words = words[0], words[1:]
    for word in words:
        increment = 1 + len(word)
        if len(current) + increment > width:
            result.append(align(current,width,alignment))
            current = word
        else:
            current = current+" "+word
    result.append(align(current,width,alignment))
    return result
# -------------------
"""
What remains to be done, is the parsing of a format string (or
"picture") and - if you like, to add the handling of multiple
paragraph (separated by a double newline) and optionally "squeezing"
several empty lines into one etc. Parsing the format string might take
a bit of work, but the rest should be trivial.
"""