Formatting a column's value output

Mitya Sirenef msirenef at
Sun Jan 27 21:50:33 CET 2013

On 01/27/2013 03:24 PM, Κώστας Παπαδόπουλος wrote:
> Τη Κυριακή, 27 Ιανουαρίου 2013  9:12:16 μ.μ. UTC+2, ο χρήστης ru... at έγραψε:
 >> <python code>
 > Yes indeed, there is no need to use a loop since i know the exact 
number of items i'am expecting. Thanks you very much for clarifying this 
to me:
 > One last thing i want to ask you:
 > ========================================
 > try:
 > cur.execute( '''SELECT host, userOS, browser, hits, lastvisit FROM 
 > WHERE counterID = (SELECT ID FROM counters WHERE URL = %s) ORDER BY 
lastvisit DESC''', (htmlpage,) )
 > except MySQLdb.Error, e:
 > print ( "Query Error: ", sys.exc_info()[1].excepinfo()[2] )
 > else:
 > data = cur.fetchall()
 > for host, useros, browser, hits, lastvisit in data:
 > print ( "<tr>" )
 > for item in host, useros, browser, hits, lastvisit.strftime('%A %e 
%b, %H:%M').decode('cp1253').encode('utf8'):
 > print ( "<td><center><b><font color=white> %s </td>" % item )
 > sys.exit(0)
 > =======================================
 > That would be also written as:
 > for row in data:
 > print ("tr>")
 > for item in row:
 > print( "blah blah blah" )
 > And that would make the code easier to read and more clear, but its 
that 'lastvisit' column's value than needs formating,hence it makes me 
use the above syntax.
 > Is there any simpler way to write the above working code without the 
need to specify all of the columns' names into the loop?

You can write:

  for row in data:
      print ("tr>")
      row = list(row)
      row[-1] = row[-1].strftime(...)
      for item in row:
          print( "blah blah blah" )

  - mitya

Lark's Tongue Guide to Python:

The existence of any evil anywhere at any time absolutely ruins a total
optimism.  George Santayana

More information about the Python-list mailing list