Structured writing to console, such as a table

  • Thread starter Raaijmakers, Vincent (IndSys, GE Interlogix)
  • Start date
R

Raaijmakers, Vincent (IndSys, GE Interlogix)

Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all the items in a string
do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined up in a console.
So:


Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was waiting for me.
A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips, references, examples...


Thanks,
Vincent
 
D

Dave Kuhlman

Raaijmakers said:
Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where
all the items in a string do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined
up in a console. So:


Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was
waiting for me. A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips,
references, examples...

This is not a solution to your problem, but is something that you
may want to know. Docutils and the reStructuredText that it
processes support the kind of ASCII tables that you describe. You
may want to check the Docutils/reStructuredText specification. If
you follow that specification you will be able to send your
tables through a Docutil tool to produces HTML, LaTeX, etc.

Docutils, by the way, is implemented in Python.

See:

http://docutils.sourceforge.net/docs/rst/quickref.html#tables
http://docutils.sourceforge.net/
https://sourceforge.net/projects/docutils/

Dave
 
P

Paul Moore

Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all
the items in a string do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined
up in a console. So:


Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was
waiting for me. A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips,
references, examples...

This is going to sound unhelpful, but I suspect the problem is that
the problem is too simple - everyone *does* reinvent the wheel,
because it's faster than going to find a generic solution.

Having said that, I didn't manage to quickly write some code for you
:)

The first question is, what does your data look like? From your
example, I'd say that you have a list of items

items = ["a", "bbbbbbbbb", "cc"]

but I'm not sure how you get your values.

Let's assume that in fact you have a "list of rows" type of
representation:

rows = [["a", 1, 2],
["bbbbbbbbb", 2, 17],
["cc", 3, 5]
]

This may or may not match your requirements, but you should be able to
either adapt my code or your data as needed.

The first problem is working out the column widths you need. That's
not difficult, just messy (because in some senses, the data is "the
wrong way round" - a list of coumns would be better for this step, but
worse later on).

def column_widths(titles, rows):
'''Calculate column widths for a "list of rows"'''

# Initialise widths to have all columns zero width to start with
widths = [len(str(title)) for title in titles]

# Adjust the width to allow space for each row in turn
for row in rows:
widths = [max(w, len(str(item)))
for w, item in zip(widths, row)]

return widths

That's a bit messy, so let's dissect it. I use list comprehensions a
lot here - if you don't know how they work, it's well worth studying
them.

We start by setting widths to fit the titles. We assume that all rows
have the same number of elements - I don't check for this.

Then, for each row, we adjust the widths to fit the items in that row.
The list comprehension goes through each column, and the new width of
that column is either the old width (if the new item fits already) or
the length of the new item (if it is the biggest so far).

For each item, we're calculating len(str(item)) which is the length of
the string representation of the item - ie, the space required on
screen for that item.

OK, that was the ugly bit - now we just format the results. This is
simple, but a little long winded.

def format(titles, rows):
"Format a table"

# First calculate the column widths
widths = column_widths(titles, rows)

# Create the result as a list of lines - it's more flexible
# than printing directly
result = []

# Title line first (add 3 spaces between colums)
line = ' '.join([t.ljust(w) for t, w in zip(titles, widths)])
result.append(line)

# Separator line (add -+- between columns)
line = '-+-'.join(['-' * w for w in widths])
result.append(line)

# Rows of data
for row in rows:
line = ' | '.join([item.ljust(w) for item, w in zip(row, widths)])
result.append(line)

return result

Now you can do:

print "\n".join(format(titles, rows))

I hope this helps. As I say, the problem is often that matching the
algorithm to what you really want is harder than writing the code in
the first place, so don't be afraid to play with this (it's nearly
midnight, so I'm offering no guarantees that this code is correct :))

Paul
 
P

Peter Abel

Raaijmakers said:
Ok, perhaps a question on a newbie level.

I try to create a simple 'write to a console application' where all the
items in a string
do have a variable size:
items = ["a", "bbbbbbbbb", "cc"]
Well, actually, I need to print a table as simple text, nice lined up in
a console.
So:


Item: Value: Another Value:
----------+----------+------------------
a | 1 | 2
bbbbbbbbb | 2 | 17
cc | 3 | 5

My hope was that somewhere in python land an existing module was waiting
for me.
A module that also prints lines, headers....

Unfortunately, I can't find it. Books, Google...
Before I reinvent this wheel... please give me some tips, references,
examples...


Thanks,
Vincent

And here comes solution No. 123.999 of xxxxxxxxx solutions :==)))
col1_text=['a', 'bbbbbbbb', 'cc']
col2_text=['1', '2', '3']
col3_text=['2', '17', '5']
headers=['Item:', 'Value:', 'Another Value:']
def print_formatted(headers,cols):
.... # len of list with headertext and
.... # len of list with columnstext must be equal
.... hl=len(headers)
.... cl=len(cols)
.... if cl <> hl:
.... print 'len(headers)=%d <> len(cols)=%d'%(hl,cl)
.... return
.... # An adhoc-function get the length of the longest text in list
.... max_strlen=lambda aList:reduce(lambda l,x:len(x)>l and len(x) or l,aList,0)
.... col_lens=[max_strlen(cols+[headers]) for i in range(cl)]
.... # Fomatstring for header
.... format= ('%%-%ds '*cl)%tuple(col_lens)
.... print format%tuple(headers)
.... # Formatstring to underline the headertext ----+------+----
.... under_line= '-+-'.join(['-'*col_lens for i in range(cl)])
.... print under_line
.... # Formatstring for the textlines
.... format = ' | '.join(['%%-%ds'%col_lens for i in range(cl)])
.... for line in zip(*cols):
.... print format%line
....
print_formatted(headers,[col1_text,col2_text,col3_text])

Item: Value: Another Value:
---------+--------+---------------
a | 1 | 2
bbbbbbbb | 2 | 17
cc | 3 | 5
Regards
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top