Formatting a column's value output

rurpy at rurpy at
Sun Jan 27 20:12:16 CET 2013

On 01/27/2013 11:44 AM, Κώστας Παπαδόπουλος wrote:
> This is not correct.
> the <a href> attribute is for url (row[0]) only, not for url and hits too.
> i want the following working code:
> =============
> 		data = cur.fetchall()
> 		for row in data:
> 			url = row[0]
> 			hits = row[1]
> 			print ( "<tr>" )
> 			print( "<td>  <a href='http://www.%s?show=log'>%s</a>  </td>" % (url, url) )
> 			print( "<td><b> %s </td>" % (hits) )
> =============
> inside the loop i posted initially, if its possible.

The easiest way is to separate them when you read 'row'
    data = cur.fetchall()
    for row in data:
        for url,hits in row:
            print ( "<tr>" )
            print( "<td>  <a href='http://www.%s?show=log'>%s</a>  </td>: % (url, hits) )
Note that sql query you used guaranties that each row will contain
exactly two items so there is no point in using a loop to go through
each row item as you would if you did not know how many items it 

But if you insist on going through them item by item in a loop, then
you need to figure out which item is which inside the loop.  One way
is like:

    data = cur.fetchall()
    for row in data:
        print ( "<tr>" )
	item_position = 0
        for item in row:
            if item_position == 0:
                print( "<td>  <a href='http://www.%s?show=log'>%s</a>  </td>:" % (item[0], item[0]))
            if item_position == 1:
                print( "<td><b> %s </td>" % item[1] )
	    item_position += 1

There are many variations of that.  You can simplify the above a 
little by getting rid of the "item_position=" lines and replacing 
"for item in row:" with "for item_position, item = enumerate (item):"  
But I think you can see the very first code example above is way 
more simple.

By the way, it would be a lot easier to read your posts if you
would snip out the extra blank lines that Google Groups adds.
There are some suggestions in

More information about the Python-list mailing list