[Tutor] quicker .strip?
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.
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())
for ip in ip_list:
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
> 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. (("10.1.1.205"),("10.1.1.206")) 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
> cursor=conn.cursor() ## Setup MySQL cursor
> cursor.execute("SELECT * FROM ip") ## My list of IP address where my
> devices are located
> ## At this point ip looks like this: (("10.1.1.205"),("10.1.1.206"))
> for x in range(len(ip)):
> 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, ",")
> 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.
> Tutor maillist - Tutor at python.org
1 Court Street, Suite 378
Lebanon, NH 03766-1358
More information about the Tutor