Skip to content Skip to sidebar Skip to footer

Formatting A List Of Text Into Columns

I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into 'normal text' is by using the string.join method. However, it

Solution 1:

Two columns, separated by tabs, joined into lines. Look in itertools for iterator equivalents, to achieve a space-efficient solution.

import string
def fmtpairs(mylist):
    pairs = zip(mylist[::2],mylist[1::2])
    return'\n'.join('\t'.join(i) for i inpairs)

print fmtpairs(list(string.ascii_uppercase))

A   B
C   D
E   F
G   H
I   J
...

Oops... got caught by S.Lott (thank you).

A more general solution, handles any number of columns and odd lists. Slightly modified from S.lott, using generators to save space.

def fmtcols(mylist, cols):
    lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols))
    return '\n'.join(lines)

Solution 2:

This works

it = iter(skills_defs)
for i in it:
    print('{:<60}{}'.format(i, next(it, "")))

See: String format examples

Solution 3:

It's long-winded, so I'll break it into two parts.

defcolumns( skills_defs, cols=2):
    pairs = [ "\t".join(skills_defs[i:i+cols]) for i inrange(0,len(skills_defs),cols) ]
    return"\n".join( pairs )

It can, obviously, be done as a single loooong statement.

This works for an odd number of skills, also.

Solution 4:

Here is an extension of the solution provided by gimel, which allows to print equally spaced columns.

deffmtcols(mylist, cols):
    maxwidth = max(map(lambda x: len(x), mylist))
    justifyList = map(lambda x: x.ljust(maxwidth), mylist)
    lines = (' '.join(justifyList[i:i+cols]) 
             for i in xrange(0,len(justifyList),cols))
    print"\n".join(lines)

which returns something like this

ACM:Aircraft Mechanic BC:Body CombatBIO:Biology CBE:Combat EngineerCHM:Chemistry CMP:ComputersCRM:Combat Rifeman CVE:Civil EngineerDIS:Disguise ELC:Electronics ... ...`

Solution 5:

data = [ ("1","2"),("3","4") ]
print"\n".join(map("\t".join,data))

Not as flexible as the ActiveState solution, but shorter :-)

Post a Comment for "Formatting A List Of Text Into Columns"