views:

90

answers:

2

I have a list of

uids: ['1234','4321','1111'] 

and I would like to turn this into a single string of:

"uid = '1234' OR uid = '4321' OR uid = '1111'"

What's the most efficient way to do this? Thanks!

+8  A: 
' OR '.join("uid = '%s'" % u for u in uids)

This invokes the join function on the string ' OR ', which takes the list passed in and puts the string in between each element, then concatenates them all together. (Used to put the ORs in between each key=val pair.)

The part inside the () is a comprehension that says "for each u in the uids list, generate a value equal to the string "uid = '%s'", but substitute in u instead of the %s marker".

Amber
I don't think it gets any better than this. +1.
Arrieta
Keep in mind that if this is for a SQL statement, a better approach is to use DB-API quoting: put "uid = ?" (for the `qmark` paramstyle) in your SQL statement instead, one for each uid, separated by OR as above, and pass the list of uids (along with any other parameters) to the `execute` method. That way you won't have to worry about getting the quoting right.
Thomas Wouters
@Thomas: Agreed. The day I discovered parameterized queries I jumped on them and never looked back.
Amber
+2  A: 

If—as Mike and Thomas mention in the comments—you need this for a database query, you should take Thomas' advice and use the DB-API.

Here are two examples:

MySQL

import MySQLdb
conn = MySQLdb.connect(host='localhost', user='u', passwd='p', db='mydb')
curs = conn.cursor()
uids = [1234,4321,1111]
qry = ("""SELECT cheese 
            FROM cheeseshop 
           WHERE id IN (%s)""" % ','.join(['%s']*len(uids)))
# 'SELECT cheese FROM cheeseshop WHERE id IN (%s,%s,%s)'
curs.execute(qry, uids)
curs.fetchone()
# ...

SQLite

import sqlite3
conn = sqlite3.connect(':memory:')
curs = conn.cursor()
uids = [1234,4321,1111]
qry = ("""SELECT cheese 
            FROM cheeseshop 
           WHERE id IN (%s)""" % ','.join('?'*len(uids)))
# 'SELECT cheese FROM cheeseshop WHERE id IN (?,?,?)'
curs.execute(qry, uids)
curs.fetchone()
# ...
Adam Bernier