Formatting a string to be a columned block of text

rzed rzantow at gmail.com
Tue Dec 26 12:57:48 EST 2006


"Dave Borne" <dborne at gmail.com> wrote in
news:mailman.2023.1167146273.32031.python-list at python.org: 

> Thanks, Paul. I didn't know about textwrap, that's neat.
> 
> Leon,
> so in my example change
>> data1= [testdata[x:x+colwidth] for x in
>> range(0,len(testdata),colwidth)] 
> to
>> data1 = textwrap.wrap(testdata,colwidth)
>> data1 = [x.ljust(colwidth) for x in data1]
> 
> oh and I made a mistake that double spaces it. the "print '\n'"
> line needs to be either
> print ''
> or
> print '\n',
> (with a comma)
> 

The solutions so far serve up text that is split within the 
confines of the column width, but leave a "ragged right" margin, 
where the line lengths appear to differ. I had the impression that 
the OP wanted right-and-left justified text, such as would 
typically be found in a newspaper column. Here's a shot at doing 
that for fixed-width fonts. To use it, first split your lines as 
others have suggested, then print aline(line,colwid) for each line 
in your data. 

# aline - align text to fit in specified width
# This module arbitrarily chooses to operate only on long-enough 
# lines, where "long-enough" is defined as 60% of the specified 
# width in this case. 
#
def aline(line, wid):
    line = line.strip()
    lnlen = len(line)
    if wid > lnlen > wid*0.6:
        ls = line.split()
        diff = wid - lnlen
        #nspaces = len(ls)-1
        eix = 1
        bix = 1
        while diff > 0: # and nspaces > 0:
            if len(ls[bix]) == 0 or ls[bix].find(' ') >= 0:
                ls[bix] += ' '
            else:
                ls.insert(bix,'')
            diff -= 1
            bix += 2
            if bix >= 1+len(ls)/2: bix = 1

            if diff > 0:
                if len(ls[-eix]) == 0 or ls[-eix].find(' ') >= 0:
                    ls[-eix] += ' '
                else:
                    ls.insert(-eix,'')
                diff -= 1
                eix += 2
                if eix >= 1+len(ls)/2: eix = 1
        line = ' '.join(ls)
    return line

-- 
rzed



More information about the Python-list mailing list