Formatting a string to be a columned block of text
Paul McGuire
ptmcg at austin.rr._bogus_.com
Tue Dec 26 09:50:46 EST 2006
"Leon" <peonleon at gmail.com> wrote in message
news:1167135267.746094.188070 at h40g2000cwb.googlegroups.com...
> Hi,
>
> I'm creating a python script that can take a string and print it to the
> screen as a simple multi-columned block of mono-spaced, unhyphenated
> text based on a specified character width and line hight for a column.
> For example, if i fed the script an an essay, it would format the text
> like a newspaper on the screen. Text processing is very new to me, any
> ideas on how I could achieve a multi-columned text formatter. Are there
> any libraries that already do this?
>
> Thanks and happy holidays!
> Leon
>
Check out the textwrap module, new in 2.3. Here is code to do one- and
two-column output.
-- Paul
gettysburgAddress = """Four score and seven years ago our fathers brought
forth on this continent, a new nation, conceived in Liberty, and dedicated
to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any
nation so conceived and so dedicated, can long endure. We are met on a great
battle-field of that war. We have come to dedicate a portion of that field,
as a final resting place for those who here gave their lives that that
nation might live. It is altogether fitting and proper that we should do
this.
But, in a larger sense, we can not dedicate -- we can not consecrate -- we
can not hallow -- this ground. The brave men, living and dead, who struggled
here, have consecrated it, far above our poor power to add or detract. The
world will little note, nor long remember what we say here, but it can never
forget what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far so
nobly advanced. It is rather for us to be here dedicated to the great task
remaining before us -- that from these honored dead we take increased
devotion to that cause for which they gave the last full measure of
devotion -- that we here highly resolve that these dead shall not have died
in vain -- that this nation, under God, shall have a new birth of freedom --
and that government of the people, by the people, for the people, shall not
perish from the earth.
""".split('\n')
import textwrap
# wrap text at 50 characters
for line in gettysburgAddress:
print "\n".join( textwrap.wrap(line,50) )
print
# create two columns of text
wrappedLines = sum([ textwrap.wrap(line,35) + ['']
for line in gettysburgAddress ],[])[:-1]
numLines = len(wrappedLines)
halfway = numLines/2
twoCol = [ "%-38s%s" % pair for pair in
zip(wrappedLines[:halfway],wrappedLines[halfway:]) ]
print "\n".join(twoCol)
More information about the Python-list
mailing list