Python module to format text into columns?

Magnus L. Hetland mlh at vier.idi.ntnu.no
Mon Nov 15 18:11:14 EST 1999


hamish_lawson at my-deja.com writes:

> 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/1999   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.

> 
> 
> Hamish Lawson

--

  Magnus          Echelon jamming noise:
  Lie             FBI CIA NSA Handgun Assault Bomb Drug Terrorism
  Hetland         Special Forces Delta Force AK47 Hillary Clinton 




More information about the Python-list mailing list