[Tutor] quicker .strip?

Lloyd Kvam pythontutor at venix.com
Fri Jan 9 15:17:48 EST 2004

fetchall returns a list of lists (well tuples, but you understand).
Effectively it's a matrix.  Your data looks a little funny because
each row is a single element.

I'd suggest:

ip = cursor.fetchall()
for x in ip:	# row by row
	for alpha in x:	# column by column
		config=getConfig(alpha)  ##Custom function that uses httplib to

There's no need to convert the row to a string and remove the characters
introduced by the conversion.  The IP address is already there as a string.

A cute coding trick for this case:

ip_list = zip(*cursor.fetchall())[0]
for ip in ip_list:
	config =getConfig(ip)

While we usually think of zip as peeling of list members in parallel it is
actually a matrix transpose function.  This converts the fetchall results
from a list of rows to a list of columns.  Your ip addresses are the first
(zeroth) column.


firephreek wrote:

> Hey, I'm brand spanking new to python, but I'm loving it.  I've begun 
> writing my first program that will run as a temperature 
> monitor/recorder.  I'm keeping track of unit IP's in a mysql database, 
> and I've written a function to pull them out, problem is when I retrieve 
> my 'list' of IP's from the databse, I get the info as a list, with each 
> IP surrounded by ( and "  i.e. ((""),(""))  and I'm 
> using strip() several times to get rid of the excess so that I can 
> re-use the IP address when gathering my data.  Here's the code, I hope 
> this all makes sense. 
> ## Setup MySQL connection:
> conn=MySQLdb.connect(host=SQLHOST, user=SQLUSER, db=SQLDATA 
> passwd=SQLPASS)    
> cursor=conn.cursor()    ## Setup MySQL cursor
> cursor.execute("SELECT * FROM ip")  ## My list of IP address where my 
> devices are located
> ip=cursor.fetchall()
> ## At this point ip looks like this: ((""),(""))
> for x in range(len(ip)): 
>         alpha=IP_strip(str(ip[x])) 
>         config=getConfig(alpha)  ##Custom function that uses httplib to 
> get a page from my device over the network.
> def IP_strip(ip):
>     alpha=string.strip(ip, ")")
>     alpha=string.strip(alpha, "(")
>     alpha=string.strip(alpha, ",")
>     alpha=string.strip(alpha,"'")
>     return alpha
> I'm wondering if there's any functions/methods that will strip the info 
> in fewer lines.  Or if there's another way of retrieving my information 
> so that I won't have to strip it.
> -Stryder
> ------------------------------------------------------------------------
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-653-8139
fax:	801-459-9582

More information about the Tutor mailing list