473,796 Members | 2,522 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Structured writing to console, such as a table

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

Jul 18 '05 #1
3 3611
Raaijmakers, Vincent (IndSys, GE Interlogix) wrote:
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 reStructuredTex t that it
processes support the kind of ASCII tables that you describe. You
may want to check the Docutils/reStructuredTex t 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...ef.html#tables
http://docutils.sourceforge.net/
https://sourceforge.net/projects/docutils/

Dave

--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
dk******@rexx.c om
Jul 18 '05 #2
"Raaijmaker s, Vincent (IndSys, GE Interlogix)" <Vi************ *****@ge.com> writes:
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(t itles, 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(t itles, 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(l ine)

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

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

return result

Now you can do:

print "\n".join(forma t(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
--
This signature intentionally left blank
Jul 18 '05 #3
"Raaijmaker s, Vincent (IndSys, GE Interlogix)" <Vi************ *****@ge.com> wrote in message news:<ma******* *************** ************@py thon.org>...
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=lamb da aList:reduce(la mbda l,x:len(x)>l and len(x) or l,aList,0)
.... col_lens=[max_strlen(cols[i]+[headers[i]]) for i in range(cl)]
.... # Fomatstring for header
.... format= ('%%-%ds '*cl)%tuple(col _lens)
.... print format%tuple(he aders)
.... # Formatstring to underline the headertext ----+------+----
.... under_line= '-+-'.join(['-'*col_lens[i] for i in range(cl)])
.... print under_line
.... # Formatstring for the textlines
.... format = ' | '.join(['%%-%ds'%col_lens[i] 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
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
457
by: Edmond Neo | last post by:
I use structured storage to store large amounts of data in various streams. I realize that I can call structured storage through a wrapper in .NET, but I'm concerned that there is a performance issue if large amounts of data are passed through the wrapper Does anyone know what is the peformance penalty of writing streams via a wrapper to the Structured Storage COM object? Does .NET intend to support Structured Storage natively instead of...
4
1948
by: nekiv90 | last post by:
Greetings, I was able to create the structured type: CREATE TYPE address_t AS ( street char(30), city char(15), state char(10), postcode smallint ) MODE DB2SQL;
3
2033
by: _link98 | last post by:
Running DB2 ESE V8.1.8 on WinXP. This is Fixpak 8. Have a structured-type and some methods for that type. One of my methods needs to do insert / update on tables. The type specification includes "LANGUAGE SQL...CONTAINS SQL". But I get SQL0374N "The MODIFIES SQL DATA clause has not been specified for the CREATE FUNCTION statement for LANGUAGE function..."
3
1810
by: HALLES | last post by:
HELLO ! in upper case: i mean to be heard ;o) Compilers are good ! Myself, i used TP6 and TP7 to work on dBASE V files, once ... a long time ago. I was unaware of Internet Usenet world, fool of me !
3
1503
by: Marius Rus | last post by:
I have a project in C# that do the followings: From an csv text file it is taking datas and inserted into an paradox database. My problem it is that when writing into the paradox database it is writing two times same datas instead of course one time. Could be a hel please?
2
2012
by: John Salerno | last post by:
I wrote this code just to experiment with writing to and reading from a file. It seems to work fine when writing, but when reading the file, it only prints the filepath to the screen, not the file contents. System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\positions.txt"); System.IO.StringReader myFile = new System.IO.StringReader(@"C:\positions.txt"); for (int i = 0; i < 3; i++)
4
2861
by: Troy | last post by:
We recently installed the .Net framework on a windows 2000 server. Shortly after that we experienced intermitant problems running a web based program that accesses an Access 2002 database. The intranet .asp program works, but as soon as it tries to access the database for normal users, it gives us an "unspecified error" and that it can't access the data base. As the administrator, I found my access was relatively stable. Anyone else...
7
2424
by: gordy | last post by:
Hey all, I have a fairly simple app which goes out to the web to download data. I want to store this data in a database (1 table, ~8 fields or so). My program is written in VB.net and works fine to get the data. My question is, how do I get the data into a database? I want to use Microsoft Access. I have seen several articles on using VB.net and ADO.net or Jet to read data in, but I haven't seen anything to write data out. Can...
12
5825
by: Steve | last post by:
I have been studying the Adjacency List Model as a means of achieving a folder structure in a project I am working on. Started with the excellent article by Gijs Van Tulder http://www.sitepoint.com/article/hierarchical-data-database My database has this basic structure: Id FolderName
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9531
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10237
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10018
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7553
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6795
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3735
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.