Formatting a string to be a columned block of text

Dave Borne dborne at gmail.com
Tue Dec 26 10:02:30 EST 2006


On 26 Dec 2006 04:14:27 -0800, Leon <peonleon at gmail.com> wrote:
> 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.

Hi, Leon,
 For putting the columns together zip is your friend. Let me lay out an example:

# get your text and strip the newlines:
testdata = file('something').read().replace('\n','')
# set some parameters (these are arbitrary, pick what you need)::
colwidth = 35
colheight = 20
numcol = 2
rowperpage = colheight * numcol
# first split into lines (this ignores word boundaries
# you might want to use somehting more like placid posted for this)
data1 = [testdata[x:x+colwidth] for x in range(0,len(testdata),colwidth)]
# next pad out the list to be an even number of rows - this will give
# a short final column. If you want them balanced you're on your own ;)
data1.extend(['' for x in range(rowsperpage - len(data1) % rowsperpage)])
# then split up the list based on the column length you want:
data2 = [data1[x:x+colheight] for x in range(0,len(data1),colheight)]
# then use zip to transpose the lists into columns
pages = [zip(*data2[x:x+numcol]) for x in range(0,len(data2),numcol)]
# finally unpack this data with some loops and print:
for page in pages:
    for line in page:
        for column in line:
            print ' %s ' % column, #<- note the comma keeps newlines out
        print '\n'
    print '\f'


-dave



More information about the Python-list mailing list