Re: Convert tuples into string

Discussion in 'Python' started by Tim Chase, Nov 26, 2012.

  1. Tim Chase

    Tim Chase Guest

    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
     
    Tim Chase, Nov 26, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    5
    Views:
    563
    Thomas J. Gritzan
    Oct 6, 2006
  2. tuples within tuples

    , Oct 26, 2007, in forum: Python
    Replies:
    12
    Views:
    596
    Dennis Lee Bieber
    Oct 27, 2007
  3. xera121
    Replies:
    8
    Views:
    738
    lolmc
    Sep 30, 2009
  4. Cameron Simpson

    Re: Convert tuples into string

    Cameron Simpson, Nov 26, 2012, in forum: Python
    Replies:
    0
    Views:
    169
    Cameron Simpson
    Nov 26, 2012
  5. Jon Reyes
    Replies:
    18
    Views:
    245
    Mitya Sirenef
    Feb 19, 2013
Loading...

Share This Page