开发者

Join list of string in python with string %s replacement

开发者 https://www.devze.com 2023-01-18 04:17 出处:网络
I have a list of ints that I want to join into a string ids = [1,2,3,4,5] that looks like \'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5\'

I have a list of ints that I want to join into a string

ids = [1,2,3,4,5]

that looks like 'Id = 1 or Id = 2 or Id = 3 or Id = 4 or ID = 5'

I have an answer now but I thought it may be good 开发者_Go百科to get the panel's opinion

Edit: More information to the nay sayers... This not generating SQL directly, this is dynamic expression that is being sent to a Ado.net data services layer that uses Entity Framework underneath. The IN clause which is what is preferred is currently not supported by the dynamic expression handler/EF4 adapter in the service yet and I have to resort to multiple equals statements for the time being.


" or ".join("id = %d" % id for id in ids)


mystring = 'id =' + 'or id ='.join(str(i) for i in ids)

If you want to generate dynamic sql as those in the comments have pointed out (don't know how I missed it), you should be doing this as

mystring = ' or '.join(['id = ?']*len(ids))  

where ? is meant to be replaced with the appropriate escape sequence for your database library. For sqlite3, that's ?. for MySQLdb, it uses the printf codes, IIRC. You can then pass the list of id's to the cursor as the second argument (usually) after the sql string and it will put them in there in a secure way. This is always the right thing.

0

精彩评论

暂无评论...
验证码 换一张
取 消