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
> "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
> 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
---- format.py ----
left = 0
center = 1
right = 2
space = width - len(line)
if alignment == center:
return ' '*(space/2) + line + \
' '*(space/2 + space%2)
elif alignment == right:
return ' '*space + line
return line + ' '*space
result = 
words = string.split(paragraph)
current, words = words, words[1:]
for word in words:
increment = 1 + len(word)
if len(current) + increment > width:
current = word
current = current+" "+word
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