Anonymous user
Align columns: Difference between revisions
→{{header|Python}}: Changed 'record' to 'row' but left zip(*matrix) for transpose instead of using map which tends to be used less in Python now (they debated removing it from Python3).
mNo edit summary |
(→{{header|Python}}: Changed 'record' to 'row' but left zip(*matrix) for transpose instead of using map which tends to be used less in Python now (they debated removing it from Python3).) |
||
Line 301:
=={{header|Python}}==
<python>from StringIO import StringIO
textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$'dollar'$character,$write$a$program
Line 308:
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'''
j2justifier = dict(L=str.ljust, R=str.rjust, C=str.center)
def aligner(infile, justification = 'L'):
''' \
Justify columns of textual tabular input where the
and the field separator is a 'dollar' character.
justification can be L, R, or C; (Left, Right, or Centered).
Return the justified output as a string
'''
assert justification in 'LRC', "justification can be L, R, or C; (Left, Right, or Centered)."
justifier = j2justifier[justification]
fieldsbyrow
# pad to same number of fields per row
maxfields = max(len(row) for row in fieldsbyrow)
fieldsbyrow = [
for
# rotate
fieldsbycolumn = zip(*fieldsbyrow)
# calculate max fieldwidth per column
colwidths =
for column in
# pad fields in columns to colwidth with spaces
for
# rotate again
fieldsbyrow = zip(*fieldsbycolumn)
return "\n".join( " ".join(row) for row in fieldsbyrow)
for align in 'Left Right Center'.split():
infile = StringIO(textinfile)
|