Convert tuples into string
Tim Chase
python.list at tim.thechases.com
Sun Nov 25 22:26:48 EST 2012
On 11/25/12 20:24, Smaran Harihar wrote:
> I was able to solve it using the following loop,
>
> conn=psycopg2.connect(connstr)
> cursor=conn.cursor()
> cursor.execute("SELECT tablename FROM pg_tables where tablename like '%"+
> inp +"%'")
> records = cursor.fetchall()
> str=""
> for rec in records:
> if str == "":
> str="".join(rec)
> else:
> m="".join(rec)
> str=str+","+m
Sounds like you want the first element of the tuple which you can
access either as "row[0]" or by unpacking the tuple into a
one-element tuple. The first would look something like
cursor.execute(...)
s = ",".join(rec[0] for rec in cursor.fetchall())
while the second would look something like
cursor.execute(...)
s = ",".join(tablename for (tablename,) in cursor.fetchall())
Note that I'm directly building the string with .join rather than
appending (the growth of which has bad performance in Python).
-tkc
More information about the Python-list
mailing list